gpt4 book ai didi

c++ - 有人可以解释吗?我有一个幸运的猜测,为什么通过引用而不是值传递这个变量会搞砸我的程序?

转载 作者:搜寻专家 更新时间:2023-10-31 01:42:16 25 4
gpt4 key购买 nike

每当我将函数“double getsales (double &num)”更改为 double getsales (double num) 并适本地更改函数原型(prototype)时,程序就会出错。我不明白为什么我的幸运猜测修复了它,无论我尝试阅读多少有关引用变量的内容。

谁能解释一下?

#include <iostream>
#include <iomanip>

using namespace std;

double getsales (double &);
void findhighest (double, double, double, double);

int main()
{
double northeast = 0;
double southeast = 0;
double northwest = 0;
double southwest = 0;

cout << "Enter NorthEast sales: $" ;
cout << getsales(northeast) << endl;
cout << "Enter SouthEast sales: $";
cout << getsales(southeast) << endl;
cout << "Enter NorthWest sales: $";
cout << getsales(northwest) << endl;
cout << "Enter SouthWest sales: $";
cout << getsales(southwest) << endl;

findhighest(northeast, southeast, northwest, southwest);

return 0;
}

double getsales (double &num)
{
do
{
if(!cin)
{
cin.clear();
cin.ignore(100, '\n');
}

cin >> num;
cout << "Number entered: ";


}while(!cin || num <= 0);
return num;
}

void findhighest (double ne, double se, double nw, double sw)
{
const char *who = "NorthEast";
double high = ne;
if(se > high)
{
who = "SouthEast";
high = se;
}
if(nw > high)
{
who = "NorthWest";
high = nw;
}
if(sw > high)
{
who = "SouthWest";
high = sw;
}

cout << fixed << showpoint << setprecision(2) << endl;
cout << who << "has the highest sale ($" << high << ")" << endl;
}

最佳答案

按值传递时,getsales 不会修改作为参数传递的原始数字。

因此,调用

findhighest(northeast, southeast, northwest, southwest);

将使用原始数字(为零)进行操作。

您应该使用修改后的值。

关于c++ - 有人可以解释吗?我有一个幸运的猜测,为什么通过引用而不是值传递这个变量会搞砸我的程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27195838/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com