在整数用户输入中输入字符不会返回错误,而是将其转换为整数?

时间:2017-10-08 21:51:45

标签: c

我写了一个程序来返回Fibonacci序列的第n个项,n是用户输入的。该程序工作正常,但我输入一个字母而不是整数来看看会发生什么,期待崩溃或错误消息,但它将字母a转换为数字6422368(它将我尝试的所有字母转换为相同的数字)。有人可以解释为什么会这样吗?

/* Fibonacci sequence that returns the nth term */

#include <stdio.h>

int main()
{
    int previous = 0; // previous term in sequence
    int current = 1; // current term in sequence
    int next; // next term in sequence
    int n; // user input
    int result; // nth term

    printf("Please enter the number of the term in the fibonacci sequence you want to find\n");
    scanf("%d", &n);

    if (n == 1) 
    { 
        result = 0;
        printf("Term %d in the fibonacci sequence is: %d", n, result);
    }

    else
    {
        for (int i = 0; i < n - 1; i++) // calculates nth term
        {
            next = current + previous;
            previous = current;
            current = next;
            if (i == n - 2) 
            {
                result = current;
                printf("Term %d in the fibonacci sequence is: %d", n, result);
            }
        }
    }
}

Screenshot of Output

1 个答案:

答案 0 :(得分:0)

使用%d输入非十进制字符时,scanf()返回0(错误)并且不设置n。当你打印它时,它是一个非初始化的变量,然后它打印随机值。

如果您想解决问题,可以将用户的输入设为string,检查其是否为正确的数字,然后将其转换为int:< / p>

#include <math.h>

int main()
{
    int previous = 0; // previous term in sequence
    int current = 1; // current term in sequence
    int next; // next term in sequence
    int n; // to catch str conversion
    int i = -1; // for incrementation
    char str[10]; // user input
    int result; // nth term

    printf("Please enter the number of the term in the fibonacci sequence you want to find\n");
    scanf("%s", &str); // Catch input as string
    while (str[++i])
        if (!isdigit(str[i])) // Check if each characters is a digit
            return -1;
    n = atoi(str); // Convert string to int

    // Rest of the function