【发布时间】:2018-09-08 18:13:40
【问题描述】:
我正在编写一个使用函数计算三个温度平均值的程序,由于某种原因,我的输出始终为 0.0。我不确定这是否与代码中变量的放置有关,或者我是否应该至少初始化其中一个,但事实是我似乎无法找出问题所在是。我对编程以及涉及函数和对象的编程仍然很陌生。这里有什么我遗漏的吗?
void getTemps(double);
double calcAvg(double tempAvg);
void displayAvg();
double temp1, temp2, temp3;
double sum;
float tempAvg;
int main()
{
getTemps(sum);
calcAvg(tempAvg);
displayAvg();
system("PAUSE");
return 0;
}
void getTemps(double sum)
{
// Get up to three temperatures
cout << "Enter temperatures of 3 cities." << endl;
cin >> temp1;
cin >> temp2;
cin >> temp3;
sum = temp1 + temp2 + temp3;
}
double calcAvg(double tempAvg)
{
tempAvg = (sum / 3);
return tempAvg;
}
void displayAvg()
{
cout << fixed << setprecision(1) << temp1 << endl;
cout << fixed << setprecision(1) << temp2 << endl;
cout << fixed << setprecision(1) << temp3 << endl;
cout << "The average temperature is " << tempAvg << " degrees." << endl;
}
【问题讨论】:
-
您需要通过引用而不是值传递
sum和tempAvg。void getTemps(double& sum)和void calAvg(double& tempAvg)。 SO上可能有这个问题的重复项。 -
你需要弄清楚是要使用全局变量还是参数传递。
-
无关:从
double切换到float用于tempAvg可能没有意义。还不如让他们都doubles。 -
尽可能避免使用全局变量。在需要的地方声明它们。
-
你在猜怎么做。别。从这些C++ books 开始。 C++ 不能靠猜测来学习。
标签: c++ function output average