gpt4 book ai didi

C++ 猜谜游戏错误

转载 作者:太空宇宙 更新时间:2023-11-04 14:41:04 25 4
gpt4 key购买 nike

我不知道如何在“int main()”的括号中声明“随机”,需要帮助。 (我是C++初学者)

请看看我的代码,尝试一下,当你认为你知道如何解决这个问题时,请告诉我一个答案。这对我来说意义重大。谢谢!同时,我也会继续努力自己解决问题。

注意:如果您想具体说明,我正在使用 Code::Blocks。

错误在我的代码的第 7/9 行

下面是我更新的代码:

#include <iostream>
#include <stdlib.h>
#include <conio.h>

using namespace std;

int main()
{
int rn = random() % 21; // generates a random int from 0 to 20

// First output asking the user to guess the number
cout << "Please guess my number :" << endl;
int u;
cin >> u;

while (u != rn) // Calculates the answer that you give
{

// If the user's number is greater than the random number
// the program will let you know it's too large
if (u > rn)
{
cout << "You guessed too big!" << endl;
}
// On the other hand, if the user guesses to small
// the program will tell them that it's too small
else if (u < rn)
{
cout << "You guessed too small!" << endl;
}

// If the user does not get the right number, the program
// will tell the user to guess again
cout << "Please guess again :" << endl;
cin >> u;

}

// If the user guesses the number correctly, the program
// will say that they got it right, and end the program
cout << "You guessed it right!" << endl;
getch();
}

这是更新后的编译器错误:

||=== 构建:在猜数字中调试(编译器:GNU GCC 编译器)===|

C:\Users\Minecraftship\Documents\CPP Programs From Book\Guess The Number\main.cpp||在'int main()'函数中:|

C:\Users\Minecraftship\Documents\CPP Programs From Book\Guess The Number\main.cpp|12|

错误:“随机化”未在此范围内声明|

||=== 构建失败:1 个错误,0 个警告(0 分钟,0 秒)===|

最佳答案

删除 main 附近的分号,编译器会准确告诉您问题所在:

int main ();

应该是

int main ()

即使修复此问题,您的代码也不会编译,因为您尚未声明 std 命名空间。您现在可以将此行放在顶部 using namespace std; 但它是 bad practice .您应该使用范围解析运算符手动声明它。

以及上面评论中已经提到的许多其他问题,请务必仔细阅读编译器输出,因为它会告诉您是哪一行导致了问题。

您的代码应如下所示:

#include <iostream>
#include <stdlib.h>
#include <conio.h>

using namespace std;

int main()
{
int rn = random() % 21; // generates a random int from 0 to 20

// First output asking the user to guess the number
cout << "Please guess my number :" << endl;
int u;
cin >> u;

while (u != rn) // Calculates the answer that you give
{

// If the user's number is greater than the random number
// the program will let you know it's too large
if (u > rn)
{
cout << "You guessed too big!" << endl;
}
// On the other hand, if the user guesses to small
// the program will tell them that it's too small
else if (u < rn)
{
cout << "You guessed too small!" << endl;
}

// If the user does not get the right number, the program
// will tell the user to guess again
cout << "Please guess again :" << endl;
cin >> u;

}

// If the user guesses the number correctly, the program
// will say that they got it right, and end the program
cout << "You guessed it right!" << endl;
getch();
}

关于C++ 猜谜游戏错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38232933/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com