带字母的 Scanf %i 给出负数?

Scanf %i with letters gives negative number?

我基本上通过解决问题解决了我的问题,但我只是想了解为什么会发生这种行为,所以首先我的代码:

#include <stdio.h>
#pragma warning(disable : 4996) // Just so MVS stops having a meltdown over scanf.

/* Simple question and answer of math equasion. */

int main() 
{
    printf("What is 5 + 5?\n\nAnswer: ");

    int userInput;
    if (scanf("%i", &userInput) && userInput != (5 + 5)) // Give 'userInput' a variable from scanf and compare to hard coded answer.
    {
        printf("\nIncorrect!\n");
        return 0;
    }

    printf("\nCorrect!\n"); // Else without the 'else'.
    return 1;
}

它很简单,是硬编码的数学问题,需要用户回答。对于已解决的匹配 userInput 的答案,预期的响应是正确的,任何不匹配的都被认为是不正确的。当我向它传递一堆字母或只是简单的“asdf”时,它认为它是正确的并吐出一个负数:-858993460.

我的解决方法是将 || userInput < 0 添加到我的 if 语句中,如下所示:

if (scanf("%i", &userInput) && userInput != (5 + 5) || userInput < 0)

所以基本上这个问题已经解决了,但我似乎无法回答这个问题:“为什么不管我输入什么字母或非数字字符,它都会吐出那个负数喂它?

如果这个问题已经得到解答,我深表歉意。我试着用我能想到的任何关键字搜索都无济于事。

scanf 函数 returns 匹配的项目数,因此在布尔内容中,如果您输入数字,则计算结果为真,否则计算结果为假。这也意味着没有值被写入userInput,所以它的值(因为它没有被初始化)仍然是indeterminate.

这意味着如果用户输入数字并且它不是 10,则您的条件表明答案是“不正确”,因此如果您没有输入数字,则认为答案是正确的.如果 either 一个数字是 not 输入 or 输入的数字是不是 10:

if (!scanf("%i", &userInput) || userInput != (5 + 5))