问题描述
我一直在调用 getgallons
函数。我试图返回 gallons
、acrearea
和 sNowdepth
,但结果总是以 0 结尾。我还想以“输入雪的深度(英寸)”来结束循环已下降(或 -1 退出):" 没有 break
。
#include <iostream>
using namespace std;
double getgallons(float sNowdepth);
int main()
{
float sNowdepth,acrearea;
double gallons;
cout << "Enter the depth (inches) of sNow that has fallen (or -1 to exit): ";
cin >> sNowdepth;
cout << "Enter the area (acres) that the sNow covers: ";
cin >> acrearea;
cout << "This amount of sNow equals " << gallons << " gallons of water." << endl << endl;
while (sNowdepth > 0)
{
cout << "Enter the depth (inches) of sNow that has fallen (or -1 to exit): ";
cin >> sNowdepth;
cout << "Enter the area (acres) that the sNow covers: ";
cin >> acrearea;
cout << "This amount of sNow equals " << gallons << " gallons of water." << endl << endl;
}
cout << "Enjoy the sNow!" << endl;
cout << "Press any key to continue...." << endl;
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(1);
gallons = getgallons(sNowdepth);
return 0;
}
double getgallons(float sNowdepth)
{
float acrearea;
double gallons;
const int WATER_galLONS = 27154;
gallons = sNowdepth * acrearea * WATER_galLONS;
return gallons;
}
解决方法
这就是你想要的。
#include <iostream>
using namespace std;
double getGallons(float snowdepth,float acrearea);
int main()
{
while (true)
{
float snowdepth,acrearea;
cout << "Enter the depth (inches) of snow that has fallen (or -1 to exit): ";
cin >> snowdepth;
if( snowdepth < 0 )
break;
cout << "Enter the area (acres) that the snow covers: ";
cin >> acrearea;
double gallons = getGallons(snowdepth,acrearea);
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(1);
cout << "This amount of snow equals " << gallons << " gallons of water.\n\n";
}
cout << "Enjoy the snow!" << endl;
return 0;
}
double getGallons(float snowdepth,float acrearea)
{
const int WATER_GALLONS = 27154;
return snowdepth * acrearea * WATER_GALLONS;
}
,
您忽略了用户对 acrearea
的输入,使用不相关且未初始化的 acrearea
来计算加仑数。
此外,您根本没有为每组用户输入计算 gallons
。您仅在用户选择结束循环后计算 gallons
。
就此而言,您为用户提供了在第一次输入时退出的选项,但您没有尊重用户是否真的选择在第一次输入时退出。
尝试更像这样的事情:
#include <iostream>
#include <iomanip>
#include <limits>
using namespace std;
double getGallons(float snowdepth,float acrearea);
int main()
{
float snowdepth,acrearea;
double gallons;
do {
cout << "Enter the depth (inches) of snow that has fallen (or -1 to exit): ";
cin >> snowdepth;
if (snowdepth > 0) {
cout << "Enter the area (acres) that the snow covers: ";
cin >> acrearea;
gallons = getGallons(snowdepth,acrearea);
cout << "This amount of snow equals " << fixed << showpoint << setprecision(1) << gallons << " gallons of water." << endl << endl;
}
}
while (snowdepth > 0);
cout << "Enjoy the snow!" << endl;
cout.ignore(numeric_limits<streamsize>::max(),'\n');
cout << "Press any key to continue...." << endl;
cout.get();
return 0;
}
double getGallons(float snowdepth,float acrearea)
{
const int WATER_GALLONS = 27154;
return snowdepth * acrearea * WATER_GALLONS;
}