JettBrain Clion中的rand()函数不起作用


#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
int correct_number , guessed_number;
correct_number = rand() ;
cout << correct_number << endl;
cout <<  "Enter your guess (0-9) : ";
cin >> guessed_number;
while (guessed_number == correct_number){
cout << "Guess is Wrong , Tre Again n"<< "Enter your guess";
cin >> guessed_number;
}
cout << "Well guessed!";
return 0;
}

这是一个我作为猜谜游戏构建的代码,用户输入一个数字作为猜测,直到它与correct_number匹配,然后它打破循环。但不知何故,它在Clion上不起作用,尽管它在一个随机的在线c++编译器上起作用。

有很多东西需要打开包装。这里有一个小代码审查:

#include <iostream>
#include <cstdlib>  // Prefer <random> for C++
using namespace std;  // Bad practice
int main() {
int correct_number , guessed_number;  // Prefer each variable on its own line
correct_number = rand() ;  // Will be the same every time; not seeded
cout << correct_number << endl;  // Prefer 'n' over std::endl
cout <<  "Enter your guess (0-9) : ";  // rand() was not constrained
cin >> guessed_number;
while (guessed_number == correct_number){  // While the guess is correct?
cout << "Guess is Wrong , Tre Again n"<< "Enter your guess";
cin >> guessed_number;
}
cout << "Well guessed!";
return 0;
}

我可以欣赏来自不同语言的人,但只有在你了解原则的情况下才能这样做。使用文档学习如何使用该语言。rand()有一个设定的范围,它不是0-9。

#include <iostream>
#include <cstdlib>
int main() {
std::cout << "Range is: 0 - " << RAND_MAX << 'n';
}

输出:

Range is: 0 - 2147483647

此外,rand()必须设置种子,并且在整个程序中只能设置一次种子。在main()开始时这样做通常就足够了。每次运行程序时,不播种将导致相同的输出。这种决定论可能有利于测试,但不利于实际使用。

但是,更好的方法是完全抛出rand(),并使用<random>中提供的类。这是更多的代码,但PRNG更好,并且将PRNG生成与您的发行版分离是可取的。

这是您的程序,已修复问题,并用<random>的功能替换了rand()

#include <iostream>
#include <random>
int main() {
int correct_number;
int guessed_number;
std::mt19937 prng{std::random_device{}()};
std::uniform_int_distribution<int> range(0, 9);
correct_number = range(prng);
std::cout << correct_number << 'n';
std::cout << "Enter your guess (0-9) : ";
std::cin >> guessed_number;
while (guessed_number != correct_number) {
std::cout << "Guess is Wrong , Try Again n"
<< "Enter your guess : ";
std::cin >> guessed_number;
}
std::cout << "Well guessed!n";
return 0;
}

输出:

❯ ./a.out 
7
Enter your guess (0-9) : 5
Guess is Wrong , Try Again 
Enter your guess : 7
Well guessed!

最新更新