【问题标题】:While loop to take user input not taking the last inputted valueWhile 循环采用用户输入而不采用最后输入的值
【发布时间】:2021-03-20 00:43:08
【问题描述】:

我对编码很陌生,所以我不太明白为什么这个 while 循环没有采用最后输入的值。如果您要输入“1, 2, 3, 4, 5”,最后的输出将是“4, 3, 2, 1”。任何帮助将不胜感激。

#include <iostream>
#include <cstdlib>
#include <queue>
#include <vector>

using namespace std;

int main()
{
    priority_queue<int> q;

    int score;

    cin >> score;

    int count = 0;

    while (count != 4)
    {
        count++;
        q.push(score);
        cin >> score;
    }

    while (!q.empty())
    {
        cout << q.top() << " ";
        q.pop();
    }
}

【问题讨论】:

  • 你永远不会在最后一个cin &gt;&gt; score; 之后q.push(score);。尝试使用调试器单步执行您的代码,看看 q 会发生什么。
  • 你的结构有点奇怪。只需将cin移到push之前,将cin移出循环,当count为5时停止循环。
  • 感谢您的帮助。我完全忘记了我在 while 循环上方还有另一个输入。
  • 有条不紊地与鸭子交谈...见How to debug small programs,别笑,它有效...

标签: c++ input while-loop


【解决方案1】:

这是因为您在第一个 while 循环中的最后一个 cin &gt;&gt; score; 之后从未执行过 q.push(score);。这意味着队列只保存 4 个整数,这导致下一个 while 循环只打印四个数字。 下面的代码会打印出五个数字。

#include <iostream>
#include <queue>

using namespace std;

int main()
{
    priority_queue<int> q;

    int score;

    int count = 0;

    while (count != 5)
    {
        cin >> score;
        q.push(score);
        count++;
    }

    while (!q.empty())
    {
        cout << q.top() << " ";
        q.pop();
    }
}

【讨论】:

    【解决方案2】:
    #include <iostream>
    using namespace std;
    
    int arr[5], n = 5;
    
    int main() {
        for (int i = 0; i < 5; i++)
            cin >> arr[i];
        for (int i = 0; i < 5; i++) {
            n--;
            cout << arr[n] << endl;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2013-11-16
      • 2020-02-15
      • 2022-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多