C++能否从数组选取随机元素?为何rand()取值固定不变
问题根因
你遇到的固定返回同一元素的问题是两个原因共同导致的:
- 没有给伪随机数生成器设置随机种子:C++标准库的
rand()是伪随机数生成函数,未显式设置种子时会默认使用固定值作为种子,每次程序运行生成的随机序列完全一致,所以每次取到的下标固定。 - 随机选取逻辑写在了全局变量初始化阶段:全局变量的初始化时机早于
main()函数执行,即使你后续在main()里补种子设置逻辑,也不会影响已经完成初始化的word变量取值。
修复步骤
- 新增两个必要头文件:
#include <cstdlib> // 提供rand()、srand()函数定义 #include <ctime> // 提供time()函数定义,用于获取系统时间作为随机种子
- 把
word变量的定义从全局作用域移到main()函数内部 - 在
main()函数最开头先调用srand(time(0))设置随机种子,再执行随机选取数组元素的逻辑
修复后完整代码
#include <iostream> #include <cstdlib> #include <ctime> using namespace std; string words[] = {"cake", "cookie", "carrot", "cauliflower", "cherries", "celery"}; string guess; int lives = 3; int main() { srand(time(0)); // 用当前系统时间作为随机种子,保证每次运行种子不同 string word = words[rand() % 6]; std::cout << "Can you guess what word I'm thinking of? I'll give you a hint: it's a food that starts with the letter C. You have three tries. Good luck!" << std::endl; while(lives > 0) { std::cin >> guess; std::cout << std::endl; if(guess == word) { std::cout << "Wow, That's actually correct! Good job!" << std::endl; break; } else { lives--; std::cout << "Nope! You now have " << lives << " lives left." << std::endl; } } if(lives <= 0) { std::cout << "And... you lose!" << std::endl; } return 0; }
补充说明
如果是使用C++11及以上版本,更推荐使用<random>库提供的随机数生成器替代rand(),生成的随机数均匀性更好,也不存在模运算带来的偏移问题。
内容的提问来源于stack exchange,提问作者Bluegenic
相关产品推荐
相关产品推荐

