无论我输入 Y 还是 N,我的程序都会在我回答“更多肉?”后结束。我期待它返回对循环的响应。
#include <iostream>
using namespace std;
int main()
{
char response = 'y';
double price;
double total = 0;
while (response == 'Y' || 'y') {
cout << "Please enter price of meat: ";
cin >> price;
total += price;
cout << "More meat? (Y/N)";
cin >> response;
return response;
}
cout << "Your total is: " << total;
return 0;
}
最佳答案
while (response == 'Y' || 'y') {
应该是
while (response == 'Y' || response == 'y') {
还有
return response;
退出整个函数(main
)。你不需要它。
I'm expecting it to return the response to the loop
您不需要(return
用于从函数返回值,终止其执行)。因此,在循环的 }
之后,下一个执行行将是 while ( condition ) ...
。如果 condition
被评估为 false
,循环将停止,下一个执行行将是循环的 }
之后的行。
关于c++ - 为什么我的 while 循环结束了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20976026/