这件事一直困扰着我好几天了:
#include <iostream>
using namespace std;
string words[] = {"cake", "cookie", "carrot", "cauliflower", "cherries", "celery"};
string word = words[rand() % 6];
string guess;
int lives = 3;
int main()
{
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;
}
我目前正在开发一个猜词游戏,但当我尝试从我的words
数组中随机选择一个元素时,它卡在了第1个元素上(即“cookie”)。我使用的代码是:
string words[] = {"cake", "cookie", "carrot", "cauliflower", "cherries", "celery"};
string word = words[rand() % 6];
需要帮助,感激不尽。
srand
初始化rand
,所以它总是返回相同的数字,我猜在你的平台上是6的倍数加1。 - Alan Birtlesmain
之外声明任何东西?对于words
,我有点明白你为什么这样做,但对于其他任何东西,这几乎没有意义,实际上会将逻辑分散到比必要更大的代码区域中,使其有点难以理解。 - fabian