rand()仅将变量设置为0
rand() only sets variable to 0
我正在玩石头、纸、剪刀游戏,我设置计算机选择的方法之一是通过rand((。I #include <ctime>
,在main的开头用srand(time(0));
播种rand,然后在函数定义中用computerWeaponChoiceV = (rand() % 3) + 1;
调用它。但是,当我测试程序时,它总是将computerWeaponChoiceV
打印为0。
我的rand()
有什么问题吗?如果你需要更多我的代码,请告诉我。
我不使用c++(只使用c++编程过两次(,但我认为问题出在rand声明上。
Try using rand() % 3 + 1;
如果这在时间(0(方面不起作用,可能需要一个"NOW"值才能正确随机化(通常编程语言需要毫秒才能随机化(。PD:我可能说的时间不对,如果这两种解决方案对你不起作用,请评论。
有一个从1到10的兰特工作的例子:
/* rand example: guess the number */
#include <stdio.h> /* printf, scanf, puts, NULL */
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
int main ()
{
int iSecret, iGuess;
/* initialize random seed: */
srand (time(NULL));
/* generate secret number between 1 and 10: */
iSecret = rand() % 10 + 1;
do {
printf ("Guess the number (1 to 10): ");
scanf ("%d",&iGuess);
if (iSecret<iGuess) puts ("The secret number is lower");
else if (iSecret>iGuess) puts ("The secret number is higher");
} while (iSecret!=iGuess);
puts ("Congratulations!");
return 0;
}
干杯!
相关文章:
- 设置变量时C++程序挂起
- 从系统("command") (C++) 设置变量
- 在构造函数中设置变量失败?
- 如何为输入设置变量编号和__android_log_print格式
- 从输入文件 c++ 中提取和设置变量
- 使用 void 函数在主函数中设置变量的值
- 未在另一个函数中设置变量引用的问题
- 对于循环设置变量为条件
- 使用 argv 设置变量
- 为什么我的代码未设置变量
- 在C++中设置变量的值之前检查变量是否更好
- 在 if 语句中设置变量
- 在子类中设置变量
- 未设置变量并返回异常数字
- 如何设置变量的 char 数组的元素数量
- C++指针运行时错误 - 使用指针设置变量然后检索
- 从C++设置变量时 QML 内存泄漏
- 使用此功能在构造函数中设置变量
- 从函数设置变量时不会更改
- 类中的二传手不会设置变量