【问题标题】:Stop while loop after using cin使用 cin 后停止 while 循环
【发布时间】:2019-02-12 13:53:27
【问题描述】:

我无法理解 while 循环的逻辑。查了很多网站,没有找到正确的答案。

我尝试在 cin 之后使用 while 循环,它显示无限输出。也尝试使用 if {break;} 但它只显示了一个输出。这是代码。

cout << "How many chambers did you find? Enter a positive number: ";
cin >> chambers;

while (chambers ){
    chambers = chambers + 1;
    boxes = (rand() % 100) + 1;
    cout << "In chamber number " << chambers << " you found " << boxes << " boxes of gold!" << endl;
}

如果输入 6 输出应该是:

In chamber number 1 you found 8 boxes of gold!
In chamber number 2 you found 50 boxes of gold!
In chamber number 3 you found 74 boxes of gold!
In chamber number 4 you found 59 boxes of gold!
In chamber number 5 you found 31 boxes of gold!
In chamber number 6 you found 73 boxes of gold!

如果输入为 6,我如何在 6 处停止?如果我输入 100 会怎样?

【问题讨论】:

    标签: c++


    【解决方案1】:

    您没有正确使用循环控制变量chambers

    在 while 循环中,0 is false!=0 is true。因此,while(chambers) 将适用于除 0 之外的所有 chambers 值。这就是无限循环的原因。

    您可以声明另一个变量来控制循环。

    示例代码将是

    cout << "How many chambers did you find? Enter a positive number: ";
    cin >> chambers;
    
    int i = 1
    while (i<=chambers ){
        boxes = (rand() % 100) + 1;
        cout << "In chamber number " << i << " you found "
        << boxes << " boxes of gold!" << endl;
        i++;
    
    }
    

    这里i将用于控制循环并给出预期的输出。

    【讨论】:

      【解决方案2】:

      在 while 循环中,如果参数为 +0、-0 或 NaN,则结果为 false;否则结果为真。 您正在输入一个正数并在循环中将其加一,从而产生无限输出

      cout << "How many chambers did you find? Enter a positive number: ";
      cin >> chambers;
      c = 0;
      while (chambers ){
            chambers = chambers - 1;
            boxes = (rand() % 100) + 1;
            cout << "In chamber number " << ++c << " you found "<< boxes << " boxes of gold!" << endl;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-03-16
        • 2021-03-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-10-31
        相关资源
        最近更新 更多