为什么算法在第一个条件之后结束

Why the algorithm end after the first condition?

本文关键字:之后 结束 条件 第一个 算法 为什么      更新时间:2023-10-16

我正在设计一种用作游戏的数字猜测算法。

谁能建议为什么算法在第一个条件之后结束?

#include <iostream>
using namespace std;
int main()
{
int num = 5;
int guess;
cout << "Guess a number n";
cin >> guess;

if (guess==num)
{
    cout << "You guessed the correct number n";
}
else if (guess < num)
{
    cout << "Your guess is lower than the number n";
    cout << "Guess again n";
    cin >> guess;
}
else
{
    cout << "Your guess is higher than the number n";
    cout << "Guess again n";
    cin >> guess;
}

return 0;

}

如果你想重复算法,你需要某种循环。

例如

#include <iostream>
using namespace std;
int main()
{
    int num = 5;
    int guess;
    cout << "Guess a number n";
    do
    {
        cin >> guess;
        if ( guess == num )
        {
            cout << "You guessed the correct number n";
        }
        else if ( guess < num )
        {
            cout << "Your guess is lower than the number n";
            cout << "Guess again n";
        }
        else
        {
            cout << "Your guess is higher than the number n";
            cout << "Guess again n";
        }
    } while ( guess != num );
    return 0;
}
如果你想

再猜一次,我推荐一个循环。否则,您的代码将按预期工作。

while(number != guess)
        {
            if(number * 2 < guess){
                cout << "Way to high. Try again." << endl;
                cin >> guess;
            }
            if(number / 2 > guess)
            {
                cout << "Tip : My number is NOT low. Try again." << endl;
                cin >> guess;
            }
            if(number < guess)
            {
                cout << "To high try something lower. Feed me a number." << endl;
                cin >> guess;
            }
            if(number > guess)
                cout << "To low, try again." << endl;
                cin >> guess;
        }