这C++猜谜游戏在语法上是否正确
Is this C++ Guessing Game syntactically correct?
#include <iostream>
#include <cstdlib>
using namespace std;
int main(){
int min = 1;
int max = 100;
int count = 0;
int randomint = min + (rand() % (int)(max - min + 1));
bool isCorrect = true;
while(!isCorrect){
int guess = 0;
cout << "What is your guess? " << endl;
cin >> guess;
if(guess < randomint){
cout << "Too low!" << endl;
count++;
} else if (guess > randomint){
cout << "Too high!" << endl;
count++;
} else{
cout << "Correct!" << endl;
cout << "Number of Guesses: " << count << endl;
isCorrect = true;
}
}
}
新C++编程。 我无法让它编译一个 IDEOne,因为它没有我需要的输入系统来运行这个程序。 我必须尽快提交这个课程,但考虑到我的大磁盘(存储我所有软件的地方)昨晚损坏了。
对于这个问题的愚蠢,我深表歉意。
是的,它在语法上是正确的,但在逻辑上不是,因为
bool isCorrect = true;
防止循环启动,应该是
bool isCorrect = false;
并且像魅力一样工作(但通过例如运行 srand(time(NULL));
来初始化随机数生成器是合理的)
你的程序在逻辑上有两个错误:
- 游戏根本不会运行,因为最初
isCorrect
是正确的。 - 随机数生成器不会获得种子,因此
rand()
每次运行时都会返回相同的值,并且randomint
始终相同。您应该事先致电srand( seed )
,其中seed
是未签名的(例如time(0)
)。
*实际上,如果您不这样做,您的游戏仍然可以运行,但是在第一次尝试后很容易被击败
相关文章:
- 特征库是否修改C++语法
- std::is_invocable 用于测试任意方法是否存在的语法(不仅是运算符())
- 标准库中的任何正则表达式语法是否支持 (?(定义)用于子模式参考?
- 放置/分段语法是否可能出现懒惰"operator or"重载?
- 统一取消引用语法是否可行?
- 结构化绑定语法是否可以在多态 lambda 中使用
- 罗斯林是否支持C++生成语法树
- 是否有任何语法可以缩短此代码
- 将任何类型的表达式放在 c++ 的初始化列表中在语法上是否正确?
- 像这样的PIMPL实现是否有任何简单的语法
- 是否有用于C++的类似 C 的语法脚本语言解释器?
- 是否可以在尾随返回类型语法中直接使用参数值(不是其类型,而是值本身)
- 是否有任何法律语法允许引号出现在 javascript 中的标识符字符旁边?(如"so")
- 是否有任何 DirectX 11 (HLSL 5.0) 等效于 DirectX 9 纹理"string function"语法?
- 是否可以避免使用lambda中的尾随返回型语法
- 是否可以通过从lambda的引用中返回T型对象,而无需使用尾随返回类型语法
- 是否可以通过与EasyLogging 相同的方式来创建一个C 类,以模仿STD :: COUT语法
- 在C 11 /14语法中,是否有可能编写lambda函数,该函数将看到父变量
- 是否允许递归BoostSpirit语法
- 此模板语法是否非法