[英]rand() function in JettBrain Clion not working
#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';
}
Output:
Range is: 0 - 2147483647
此外, rand()
必须播种,并且在整个程序中只播种一次。 在main()
的开头这样做通常就足够了。 每次运行程序时,不播种将导致相同的 output。 这种确定性可能有利于测试,但不适用于实际使用。
但是,更好的是完全抛弃rand()
并使用<random>
中提供的类。 它的代码有点多,但 PRNG 更好,并且希望将 PRNG 生成与您的发行版分开。
这是您的程序,修复了问题,并将rand()
替换为<random>
的功能。
#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;
}
Output:
❯ ./a.out
7
Enter your guess (0-9) : 5
Guess is Wrong , Try Again
Enter your guess : 7
Well guessed!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.