【问题标题】:Why is my while loop ending?为什么我的 while 循环结束了?
【发布时间】:2014-01-25 09:29:00
【问题描述】:

无论我输入 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;

}

【问题讨论】:

  • (response == 'Y' || 'y') 应该是 (response == 'Y' || response =='y')

标签: c++ loops while-loop return response


【解决方案1】:
while (response == 'Y' || 'y') {

应该是

while (response == 'Y' || response ==  'y') {

还有

return response;

退出整个函数 (main)。你不需要它。


我希望它能够将响应返回给循环

您不需要(return 用于从函数返回值,终止其执行)。因此,在循环的} 之后,下一个执行的行将是while ( condition ) ...。如果condition 被评估为false,则循环将停止,下一个执行的行将是循环的} 之后的行。

【讨论】:

  • 具有讽刺意味的是,while 循环的条件与它退出的原因无关,因为所写的条件基本上是一个while(true) 循环。 return 是实际答案。
  • @Mgetz - 是的,但这两件事仍然是个问题:)
【解决方案2】:

你的缩进被破坏了,你的 while() 测试也是如此,你有一个虚假的 return 声明:

#include <iostream>
using namespace std;
int main()
{

    char response = 'y';
    double price;
    double total = 0;
    while (response == 'Y' || response == 'y') {

        cout << "Please enter price of meat: ";
        cin >> price;

        total += price;

        cout << "More meat? (Y/N)";
        cin >> response;
    } // end while
    cout << "Your total is: " << total;

    return 0;
} // end main()

(使用do ... while() 会稍微简洁一些,而且您不需要将response 初始化为'y')。

【讨论】:

    猜你喜欢
    • 2014-03-24
    • 2019-06-16
    • 2017-04-18
    • 2020-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-07
    • 1970-01-01
    相关资源
    最近更新 更多