C++猜测游戏错误

0 c++ compiler-errors

我不知道如何在"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();
}
Run Code Online (Sandbox Code Playgroud)

这是更新的编译器错误:

|| === Build:Guess中的调试编号(编译器:GNU GCC编译器)=== |

C:\ Users\Minecraftship\Documents\CPP程序来自Book\Guess Number\main.cpp || 在函数'int main()'中:|

C:\ Users\Minecraftship\Documents\CPP程序来自Book\Guess Number\main.cpp | 12 |

错误:未在此范围中声明'randomize'

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

ifm*_*fma 10

删除main附近的分号,编译器正在告诉你究竟是什么问题:

int main ();
Run Code Online (Sandbox Code Playgroud)

应该

int main ()
Run Code Online (Sandbox Code Playgroud)

由于您尚未声明std命名空间,因此即使在修复此代码之后,您的代码也将无法编译.你现在可以把这条线放在顶部,using namespace std;但这是不好的做法.您应该使用范围解析运算符手动声明它.

并且上面的注释中已经提到过许多其他问题,请确保彻底阅读编译器输出,因为它会告诉您导致问题的行.

您的代码应如下所示:

#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();
}
Run Code Online (Sandbox Code Playgroud)