c++ - 数组变量返回意外值

标签 c++ arrays dynamic-arrays

我正在尝试将数组传递给函数 (*getcreditcurve)。我期望函数 (*getcreditcurve) 返回一个数组。 Main 函数应该发送几个这样的数组给函数 (*getcreditcurve),指针函数应该使用指针函数 (*getcreditcurve) 中给出的逻辑为不同的数组返回一个数组给 main 函数。我没有收到错误,但我没有得到正确的值。我希望 I+1 为 3 * 0.0039 = 0.0117 而 I+2 为 4 *0.0060 = 0.0024 但是我在 excel 输出中得到以下信息

'00D4F844   00D4F84C'

即使我将打印语句更改为

'print << *(I1+1) << '\t' << *(I2+2) << endl;'

我得到以下 excel 输出

-9.26E+61   -9.26E+61

有人可以帮忙解决问题吗?抱歉,我浏览了该站点中的其他帖子/问题,但无法找到解决此问题的最简单方法。我将使用此逻辑来构建其他项目,以便简化问题以解决主要问题。

#include<iostream>
#include<cmath>
#include<fstream>
typedef double S1[5];
using namespace std;
double *getcreditcurve(double *);

int main()
{


S1 C1 = { 0.0029, 0.0039, 0.0046, 0.0052, 0.0057 };
S1 C2 = { 0.0020, 0.0050, 0.0060, 0.0070, 0.0080 };

typedef double *issuer;
issuer I1 = getcreditcurve(C1);
issuer I2 = getcreditcurve(C2);


ofstream print;
print.open("result1.xls");
    print << (I1+1) << '\t' << (I2+2) << endl;

    print.close();
    return 0;


}

double *getcreditcurve(S1 ptr)
{
const int cp = 5;
typedef double curve[cp];
curve h;

h[0] = 2 * ptr[0];
h[1] = 3 * ptr[1];
h[2] = 4 * ptr[2];
h[3] = 5 * ptr[3];
h[4] = 6 * ptr[4];

return h;
}

最佳答案

如果您希望 getcreditcurve 返回一个数组,那么试试这个:

const int cp = 5;
typedef double curve[cp];
curve getcreditcurve(S1 ptr) {

但这会产生错误 error: ‘foo’ declared as function returning an array。函数不能返回 C 数组。但好消息是,如果您完全接受 C++,则可以返回 std::array

#include<array>
const int cp = 5;
typedef curve std::array<double,cp>;
curve getcreditcurve(S1 ptr) {

但实际上,std::vector 可能更好,因为您对大小有更大的灵 active 。

#include<vector>

std::vector<double> getcreditcurve(std::vector<double> ptr)
{
    std::vector<double> h;
    h.push_back(2 * ptr.at(0));
    h.push_back(3 * ptr.at(1));
    h.push_back(4 * ptr.at(2));
    h.push_back(5 * ptr.at(3));
    h.push_back(6 * ptr.at(4));

    return h;
}

事实上,几乎所有与 C 数组有关的问题都可以通过 std::vector 来解决。然后,在特殊情况下,你可以使用std::array。但现在关注 std::vector

关于c++ - 数组变量返回意外值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31362360/

相关文章:

c++ - 程序执行时间计数器

c++ - wxWidgets 获取窗口

c++ - OpenGL 正在使用最后加载的纹理

excel - 如何在 Excel 中将 SUM 函数与(新)动态数组一起使用

c - 将 .txt 文件中的字符串读入动态数组

c - 通过 C 中的方法动态分配和填充变量

c++ - 如何允许用户重新配置编译器以与 cmake 一起使用?

python - 将函数应用于 3D numpy 数组

arrays - 如何在不减慢过程的情况下使用颜色为文本着色?

javascript - 如何将对象的对象转换为对象的数组?