再次使用相同的随机数

编程入门 行业动态 更新时间:2024-10-26 17:25:24
本文介绍了再次使用相同的随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我已经制作了这个随机程序,但我一直得到与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随机化(种子化)伪随机数生成器,如下面的代码示例所示: www.cplusplus/reference/clibrary/cstdlib/rand/ [ ^ ]. 每个运行时间只能执行一次!
—SA
Randomize (seed) the pseudo-random number generator using srand, as shown in the code sample below: www.cplusplus/reference/clibrary/cstdlib/rand/[^]. Do it only once per run time!
—SA

更多推荐

再次使用相同的随机数

本文发布于:2023-11-08 08:06:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1568816.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:随机数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!