C rand()函数不生成随机数

use*_*355 -1 c random numbers

我是编程新手.我需要能用C生成随机数的东西.我找到了"rand()".但它不会产生随机值.请检查以下简单代码.

以下代码给出

roll the first dice : 6
roll the second dice : 6
roll the third dice : 5
Run Code Online (Sandbox Code Playgroud)

这是代码:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>


int main()
{

  int dice1,dice2,dice3,total1,total2;
  char prediction[10];

int dice_generator()
{
  dice1= (rand()%6)+1;
  printf("roll the first dice: %d \n", dice1);
  dice2= (rand()%6)+1;
  printf("roll the second dice: %d \n", dice2);
  dice3= (rand()%6)+1;
  printf("roll the third dice: %d \n", dice3);

  return 0;
}

  dice_generator();
  total1 = dice1+dice2+dice3;
  printf("final value is = %d\n",total1);
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

Ste*_*mit 8

你需要"种子"随机数发生器.试着打电话

srand(time(NULL));
Run Code Online (Sandbox Code Playgroud)

一旦在你的程序的顶部.

(有更好的方法,但这应该让你开始.)

  • 如果您觉得答案有帮助,您应该接受最佳答案.它是网站流量的一部分,让未来的观众知道如何解决问题:) (2认同)