C++随机猜数游戏错误
C++ Random Number Guessing Game Errors
所以,我必须从一个随机猜谜游戏中编写一个程序。程序需要要求玩家猜测1-100之间的数字。必须至少使用一个函数。它需要告诉玩家他们是否太低/太高,要求他们再试一次,或者如果他们猜到了,请他们再玩一次。
我有一些我无法弄清楚的错误。
44:错误:"int winlose"重新声明为不同类型的符号 9:错误:之前声明"int winlose(int(" 44:错误:"g"未在此范围内声明
法典
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int winlose(int);
int main()
{
int g, n, x;
while (x!=0)
{
do
{
srand(time(NULL));
n = 1 + rand()%100;
cout<<"Welcome to the guessing game. I have a number between 1-100.
Can you guess it?"<<endl;
cout<<"Please enter your guess"<<endl;
cin>>g;
winlose(g);
} while (n!=0);
cout<<"Play again? Enter 0 for no, any other number for yes."<<endl;
cin>>x;
}
return 0;
}
int winlose(g)
{
if (g<n)
{
cout<<"Your guess is too low. Try again."<<endl;
cin>>g;
}
else if (g>n)
{
cout<<"Your guess is too high. Try again."<<endl;
cin>>g;
}
else (g=n)
{
cout<<"Congrats! You win. The number was "<<n<<endl;
n=0;
}
return g;
return n;
}
除了函数声明之外,您还犯了一些错误。 函数声明必须包含每个参数的类型,因此正确的方法是:
int winlose(int g);
不能在 else 语句中使用条件:(else (g=n)
(。如果前面的条件(if
和else if()
中的条件(都不满足,则 else 语句是一个包罗万象的语句。如果只希望在特定条件下触发此操作,请使用其他else if()
。您不需要在每个if
声明的末尾都有else
;以else if(){...}
结尾是完全正确的.
您还需要与'=='
进行比较,而不是'='
。=
是赋值运算符,g=n
会将 g 的值设置为 n。如果要检查g是否等于n,则必须使用g==n
您应该在外部循环中调用srand()
,否则每次猜测后,值都会更改。
其余部分经过校正,有时会稍作更改以使其性能正确:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
bool winlose(int number, int givenNumber);
int main(){
int g, n, x;
bool guessed;
do {
srand(time(NULL));
n = 1 + rand()%100;
cout<<"Welcome to the guessing game. I have a number between 1-100. Can you guess it?"<<endl;
do {
cout<<"Please enter your guess"<<endl;
cin>>g;
guessed = winlose(g, n);
} while (!guessed);
cout<<"Play again? Enter 0 for no, any other number for yes."<<endl;
cin>>x;
} while (x!=0);
return 0;
}
bool winlose(int g, int n) {
if (g<n) {
cout<<"Your guess is too low. Try again."<<endl;
return false;
}
else if (g>n) {
cout<<"Your guess is too high. Try again."<<endl;
return false;
}
else {
cout<<"Congrats! You win. The number was "<<n<<endl;
return true;
}
}
相关文章:
- 我是 c++ 的新手.学习基本知识后,我想做井字游戏.对于印刷板,我在下面写代码,但它显示错误
- 我在贪吃蛇游戏中收到了错误代码 -1073741571
- 我的游戏引擎的 spdlog 日志记录出现奇怪的"unresolved external symbol"错误
- C++ 中连接 4 游戏的输入逻辑错误
- Visual Studio 中的 lcr 游戏 c++ LINK 2019 错误
- 游戏引擎 SFML C++错误
- C++ do/while 循环和 if/else: 骰子游戏 -- 第 75 行错误:"Cout"之前的预期"While" -- 如何解决这个问题?
- C++随机猜数游戏错误
- 井字游戏中的错误
- 我正在尝试安装游戏引擎,但遇到错误
- 致命错误LNK1169:在C++Visual Studio中编写战舰游戏时发现的一个或多个多重定义的符号
- C++ 抛出读取访问冲突错误,但我不确定为什么。平铺滑块益智游戏
- 如何使用运行时检查错误来修复我的C 格斗游戏
- 我在使用C 的Hangman游戏中遇到错误
- C TIC TAC TOE游戏.开关空间而不是错误消息
- 我正在尝试学习使用 SDL 制作游戏。我的书教SDL1.2.3,我无法让它在Visual Studio上工作。谁能帮忙?我的错误:
- C 猜测游戏错误与某事
- 使用日食的猜谜游戏C++:错误
- 骰子游戏c++错误未声明的标识符/代码审查
- C++猜游戏错误