再次使用相同的随机数 [英] same random number again

查看:62
本文介绍了再次使用相同的随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我已经制作了这个随机程序,但我一直得到与41相同的答案.每次运行程序时,每次获得1到100之间的随机数的帮助都会有用,而不仅仅是41.

Hi,

I have made this random program but I am keep getting the same answer as 41. Any help to get a random number between 1 to 100 each time I run the program rather then 41 only.

void main()
{
	int userData;
	int random;

	printf("\t\t\t Lotto Game \n");
	printf("\t\t\t ---------- \n\n");
	printf("Enter a number to see if you have win a price : ");
	scanf("%d%*c",&userData);
	random = rand() ;
	
	if (userData > random)
	{
		printf("Your entry is higher\n");

	}

	else if (userData < random)
	{
		printf("Your entry is lower\n");
	}

	else 
	{
		printf("Corrent answer, you are a winner :-)\n");
	}

	printf("Correct answer is %d \n",random);


	system("pause\n");

}

推荐答案

由于您只在程序中执行一次此操作,因此通常会返回相同的数字.您需要通过 srand() [ ^ ]函数,使用种子唯一的值,例如当前时间是一个合理的选择.
Since you are only doing this once in your program it will generally return the same number. You need to seed the randomiser via the srand()[^] function, using a seed value that is unique, something like the current time would be a reasonable choice.


您可以从 ^ ],您需要初始化随机数生成器(使用 srand函数 [ ^ ]).

参考链接中的示例:
As you can read from this[^] you need to initialize the random number generator (using the srand function[^]) before calling the rand function it.

Example from the reference link:
/* rand example: guess the number */
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main ()
{
  int iSecret, iGuess;

  /* initialize random seed: */
  srand ( time(NULL) );

  /* generate secret number: */
  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;
}


使用srand随机化(种子化)伪随机数生成器,如下面的代码示例所示:
http://www.cplusplus.com/reference/clibrary/cstdlib/rand/ [ ^ ].

每个运行时间只能执行一次!

—SA
Randomize (seed) the pseudo-random number generator using srand, as shown in the code sample below:
http://www.cplusplus.com/reference/clibrary/cstdlib/rand/[^].

Do it only once per run time!

—SA


这篇关于再次使用相同的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆