-1

我有一个关于 C++ 函数编程的简单(给你)问题。我声明以下功能:

double Function (double x,
                     double y,
                     double z,
                     double k,
                     double u)
Do things...
double array[1];
return array[0]=value1;
return array[1]=value2;

现在main(){}我想输出这两个值。所以,我去:

    double result[1] = {SimpleMonteCarlo(x,
                                  y,
                                  z,
                                  k,
                                  u)};
cout << "the first result is " << result[0] << "\n";
cout << "the second result is" << result[1] << "\n"

但是,看起来只有result[0]( array[0]) 具有正确的值。如果我再次将 value2 设置为array[0]没有问题。

关于如何绕过它的任何想法?最重要的是,为什么会发生这种情况?

非常感谢你们的努力!:)

4

3 回答 3

3

在 C++ 中,不能从函数返回数组。您通常应该使用的是std::vector

std::vector<int> SimpleMonteCarlo()
{
    std::vector<int> vec;
    vec.push_back(42);
    vec.push_back(1337);
    return vec;
}

std::vector<int> vec = SimpleMonteCarlo();
std::cout << vec[0] << " " << vec[1] << std::endl;
于 2013-06-15T18:21:16.440 回答
0

In your function, you are returning only one value.

double Function (double x,
                     double y,
                     double z,
                     double k,
                     double u) {
//do some stuff
double array[1];
return array[0]=value1;
return array[1]=value2; //this line is never executed... so it can be written in code, but has no effect. Its same as if it were comment out
}

There is no problem with inner array. Hovewer, your logic is incorrect. In your code

double result[1] = {SimpleMonteCarlo(x,
                                  y,
                                  z,
                                  k,
                                  u)};
cout << "the first result is " << result[0] << "\n";
cout << "the second result is" << result[1] << "\n"

You have problem with last line. You are trying to read value result[1], that never exists. And having array only for 1 item is useless and bad design.

于 2013-06-15T18:24:49.563 回答
0

返回一个在堆栈上创建的数组,因为您的上述代码非常危险,并且很可能导致数据损坏。我建议你使用一个参数来返回你的结果,如下所示:

void Function(double x, double y, double output[2])
{
     //Do your calculations
     output[0] = value0;
     output[1] = value1;
}

你会这样调用函数:

double retVal[2];
Function(x, y, retVal);
cout << retVal[0] << retVal[1];

另一种方法是在函数内部的堆上分配一个数组并返回它;但在这种情况下,调用者必须释放数组(意味着额外的程序员工作和小心!)。恕我直言,对于像您这样的简单情况,第一种类型的声明函数更好。

于 2013-06-15T18:17:43.110 回答