为什么算法在第一个条件之后结束
Why the algorithm end after the first condition?
我正在设计一种用作游戏的数字猜测算法。
谁能建议为什么算法在第一个条件之后结束?
#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;
}
相关文章:
- 为什么在popback()操作之后,它仍然打印完整的矢量
- 在类定义之后定义一个私有方法
- 为什么在这个代码结束循环中没有得到结束
- 在循环C++中指定字符串之后,不会打印该字符串
- C++宏忽略之后的内容
- 试图对缓存进行跨步测试,但程序并没有结束
- 要与"if constexpr"一起使用的编译时消息(在预处理器之后)
- 当调用switch语句中的函数时(即使函数不包含循环),似乎是永不结束的循环的问题
- 为什么擦除方法会影响结束方法
- 根据用户输入用字母填充矢量,并将"开始"和"结束"放在四肢
- strncpy之后的char数组的错误行为
- 计算十进制 c++ 之后的数字
- 删除映射和分割错误中的一个过去结束元素
- "x += x--"之后的 x 是什么?
- kill() 总是返回 0(成功),即使在子进程已经结束之后?
- C 程序在CIN之后突然结束
- 范围之后的交易结束
- 为什么算法在第一个条件之后结束
- C -在main()结束之前/之后运行函数
- 不允许绑定到初始化列表中的引用的临时存在于actor结束之后的理由是什么?