C++:提示需要多次输入数据才能继续

标签 c++ random cin

我编写的以下程序提示用户输入一个 1 - 100 的数字。该程序有一个来自随机数生成器的预选数字,用户必须猜测该数字。如果用户的猜测太高或太低,那么程序将通知用户,直到用户的猜测是正确的。我的程序运行良好,但是当提示输入数字时,在某些情况下我必须输入数字四次或更多次,程序才会提示我。有人可以告诉我或帮助我找出我的错误吗?

#include <iostream>
#include <ctime>//A user stated that using this piece of code would make a true randomization process.
#include <cstdlib>
using namespace std;

int main()//When inputing a number, sometimes the user has to input it more than once.
{
    int x;
    int ranNum;
    srand( time(0));

    ranNum = rand() % 100 + 1;

    cout << "Please input your guess for a random number between 1 - 100.\n";
    cin >> x;

    while (x > ranNum || x < ranNum)
    {
        {
            if (x > ranNum)
                cout << "Your input was greater than the system's generated random number. Please try again.\n";
            cin >> x;
            if (x > 100 || x < 1)
                cout << "Input invalid. Please input a number between 1 - 100.\n";
            cin >> x;
        }
        {
            if (x < ranNum)
                cout << "Your input was less than the system's generated random number. Please try again.\n";
            cin >> x;
            if (x > 100 || x < 1)
                cout << "Input invalid. Please input a number between 1 - 100.\n";
            cin >> x;
        }
        {
            if (x == ranNum)
                cout << "You guessed right!\n";
        }
    }

    return 0;
}

最佳答案

你的括号放错地方了。具有多行的 if 语句应采用以下形式:

if (condition)
{
    code1
    code2
    code3
    ...
}

你拥有的是

{
    if condition
        code1
        code2
        code3
        ...
}

所以 code1仅在条件为真但code2 时运行, code3其余的无论如何都会运行。缩进在 C++ 中没有任何意义。我们可以(请永远不要这样做):

            if (condition)
    {
code1
code2
        code3
}

所有三行都将在 if 语句中运行。

您的代码已更正为将括号放在正确的位置

while (x != ranNum)
{
    if (x > ranNum)
    {
        cout << "Your input was greater than the system's generated random number. Please try again.\n";
        cin >> x;
        if (x > 100 || x < 1)
        {
            cout << "Input invalid. Please input a number between 1 - 100.\n";
            cin >> x;
        }
    }
    if (x < ranNum)
    {
        cout << "Your input was less than the system's generated random number. Please try again.\n";
        cin >> x;
        if (x > 100 || x < 1)
        {
            cout << "Input invalid. Please input a number between 1 - 100.\n";
            cin >> x;
        }
    }
    if (x == ranNum)
        cout << "You guessed right!\n";
}

我也改了while (x > ranNum || x < ranNum)while (x != ranNum)因为我们只想在 x 时运行循环不等于 ranNum

关于C++:提示需要多次输入数据才能继续,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34399792/

相关文章:

java - 依赖于抛硬币的 while 循环的预期运行时间是多少?

algorithm - ARM 汇编的 PRNG?

c++ - Eclipse CDT 顾问中的奇怪输出

c++ - 运算符重载 >> 和私有(private)成员

c++ - EXC_BAD_ACCESS 在字符串流对象上使用 <<

c++ - 我的文件服务器程序已失效的僵尸进程

algorithm - rBST 的计算概率

c++ - 跳过 cin.get() 和 cin.ignore()

c++ - 将数据从 stringstream 存储到 unsigned long 中的可能方法是什么?

c++ - GCC 是如何实现 C++ 标准分配器的?