C随机数产生垃圾值

时间:2017-01-29 06:25:42

标签: c random

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main() {

    srand(time(0)); 

    int random = 0, guess, guesses = 1;
    random = rand() % 100 + 1;
    printf("The number has been generated. Input 0 to quit.\n");
    do {
        scanf("%d", &guess); //takes user input for guess
        if (guess > random && guess != 0)
            printf("Lower!\n");
        else
        if (guess < random && guess != 0)
            printf("Higher!\n");
        else
        if (guess == random) {
            printf("Bingo!");
            return 0;
        } else
        if (guess == 0) {
            printf("Thanks for playing, the number was %d\n", &random);
            return 0;
        }
        guesses++;
    } while (guesses != 6); //maximum of 5 guesses

    printf("Thanks for playing, the number was %d\n", &random);

    return 0;
}

每当我在已生成数字时显示随机变量时,将输出垃圾值。但是代码片段用于检查猜测和随机数之间的比较,我似乎无法正确输出随机数。

2 个答案:

答案 0 :(得分:4)

%d中的

printf期望参数为int数据类型。您正在传递int *数据类型(&random) 在最后两个&中删除random之前的printf

printf("Thanks for playing, the number was %d\n", random);

答案 1 :(得分:0)

您应该传递random的值而不是其地址:

printf("Thanks for playing, the number was %d\n", random);

另请注意,您应该检查scanf()的返回值:如果您键入一个字母,程序将具有未定义的行为,它可能会在迭代5次后退出,或者永远迭代或完全执行其他操作。

以下是改进版本:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(void) {
    int random, guess, guesses;
    srand(time(0)); 

    random = rand() % 100 + 1;
    printf("The number has been generated. Input 0 to quit.\n");
    for (guesses = 0; guesses < 5; guesses++) {
        // take user input for guess
        if (scanf("%d", &guess) != 1 || guess == 0)
            break;

        if (guess > random) {
            printf("Lower!\n");
        } else
        if (guess < random) {
            printf("Higher!\n");
        } else {
            printf("Bingo!\n");
            return 0;
        }
    }

    printf("Thanks for playing, the number was %d\n", random);

    return 0;
}