gpt4 book ai didi

c - 生成给出相同数字的随机数

转载 作者:行者123 更新时间:2023-11-30 19:07:40 26 4
gpt4 key购买 nike

在为类(class)编写程序时,我必须为其一部分创建一个随机数生成器,每当我运行它时,随机数生成器只会生成相同的数字,即“293”。

我已经删除了生成数字的代码并将其单独放置在一个新程序中,并且它正确地生成了不同的数字。代码中是否有其他内容导致每次输出都相同?

int main(){

/*generates random number*/
int min = 100;
int max = 999;
int num = rand()%((max+1)-min)+min;
printf("number is: %d\n",num);

int input;

/*takes apart the generated number*/
int digitThree = num % 10 /1;
int digitTwo = num % 100 / 10;
int digitOne = num % 1000 / 100;

printf("Today we will play a game, you take ten guesses of a 3 digit number, and I will tell you which one is a match or a hit\n");

for(int i = 1; i<11; i++){

printf("\nGuess #%d.\n", i);
printf("What is your guess?\n");
scanf("%d", &input);

int inputThree = input % 10 /1;
int inputTwo = input % 100 / 10;
int inputOne = input % 1000 / 100;

/*checks if number is a hit or a match*/
if (inputThree == digitThree )
printf("Numer %d is a match\n", inputThree);
if(inputThree == digitTwo)
printf("Number %d is a hit\n", inputThree);
if(inputThree == digitOne)
printf("Number %d is a hit\n", inputOne);
if(inputTwo == digitThree)
printf("Number %d is a hit\n", inputTwo);
if(inputTwo == digitTwo)
printf("Number %d is a match\n", inputTwo);
if(inputTwo == digitOne)
printf("Number %d is a hit\n", inputTwo);
if(inputOne == digitThree)
printf("Number %d is a hit\n", inputOne);
if(inputOne == digitTwo)
printf("Number %d is a hit\n", inputOne);
if(inputOne == digitOne)
printf("Number %d is a match\n", inputOne);

if(inputOne == digitOne && inputTwo == digitTwo && inputThree == digitThree){
printf("Congrats! You guessed the number %d correctly!\n", num);
return 0;
}

if(i == 10)
printf("Last Guess!!\n");
printf("\n");

}

最佳答案

您必须使用srand()函数:

#include <time.h>

int main(){
time_t t;

/* Initialization to get random differents numbers each time */
srand((unsigned) time(&t));

/*generates random number*/
int min = 100;
int max = 999;
int num = rand()%((max+1)-min)+min;
printf("number is: %d\n",num);

链接-> https://www.tutorialspoint.com/c_standard_library/c_function_srand.htm

关于c - 生成给出相同数字的随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46535091/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com