生成相同数字的随机数

时间:2017-10-02 23:27:06

标签: c random

在为课程编写程序时,我必须为其中的一部分创建一个随机数生成器,每当我运行它时,随机数生成器将只生成相同的数字,即" 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");

}

1 个答案:

答案 0 :(得分:1)

您必须使用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);

链接 - &gt; https://www.tutorialspoint.com/c_standard_library/c_function_srand.htm