简体   繁体   English

为什么变量在比较时变为零?

[英]Why variable does change to zero when it is compared?

I have the code below. 我有下面的代码。 The problem is with variable r , which first holds a random number between 1-10. 问题出在变量r ,它首先拥有1-10之间的随机数。 Later it is compared inside a loop to a user input number. 之后,将其在循环内与用户输入数字进行比较。 The loop ends when the user guesses the randomly generated number. 当用户猜测随机生成的数字时,循环结束。

I am using short type for the guess, and int for the randomly generated number r . 我使用short类型进行猜测,使用int表示随机生成的数字r The point is that after the first guess of the user, r becomes 0 and I don't know why. 关键是在用户的第一次猜测之后, r变为0,但我不知道为什么。 This problem does not happen if guess is an int . 如果guessint则不会发生此问题。

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

int main(int argc, const char * argv[]) {
    srand(time(NULL));
    int r = (rand()%10)+1;
    short guess = -1;
    printf("%d\n", r);
    while ((guess)!= r){
        printf("%d\n", (int) guess);
        printf("%d\n", guess);
        printf("%d\n", r);
        printf("Give me a number from 1 to 10: ");
        scanf("%d",&guess);
        if (guess> r){
            printf("The number is lower\n");
        }
        else if (guess<r){
            printf("The number is higher\n");
        }
        else {
            printf("Corrent!\n");
        }
    }
    return 0;
}

An output example would be: 输出示例为:

7
-1
-1
7
Give me a number from 1 to 10: 5
The number is lower
5
5
0
Give me a number from 1 to 10: 

The problem is here: 问题在这里:

scanf("%d",&guess);

The variable guess is a short , but the %d format specifier to scanf expect a pointer to an int . 变量的guessshort ,但是scanf%d格式说明符期望指向int的指针。 Using the wrong format specifer to printf or scanf invokes undefined behavior . 使用错误的格式说明符对printfscanf调用未定义的行为

What most likely happened is that an int on your system is larger than a short , resulting in writing to bytes in memory past where guess resides, overwriting nearby variables, in this case r . 最有可能发生的情况是系统上的int大于short ,导致写入guess所在的内存字节,并覆盖附近的变量(在本例中为r This behavior however is not guaranteed and could change with seemingly unrelated code changes. 但是,不能保证此行为,并且可能会因看似无关的代码更改而改变。

Either use the correct format specifier: 使用正确的格式说明符:

scanf("%hd",&guess);

Or change the type of guess to int . 或将guess类型更改为int Since there's no real reason to use a short here, I'd recommend the latter. 由于这里没有使用short真正原因,因此我建议使用后者。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM