rand()仅将变量设置为0

rand() only sets variable to 0

本文关键字:设置 变量 rand      更新时间:2023-10-16

我正在玩石头、纸、剪刀游戏,我设置计算机选择的方法之一是通过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;
}

干杯!