2017-10-08 63 views
-1

我写了一个程序返回斐波纳契数列的第n项,n是用户输入的。该程序工作正常,但我输入了一个字母而不是一个整数,看看会发生什么,期待崩溃或错误信息,但它将字母a转换为数字6422368(它将所有我试过的字母转换为相同的数字)。有人能解释为什么发生这种情况吗?在整数用户输入中输入char不会返回错误,而是将其转换为整数?

/* 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

+5

你是否检查'scanf函数的返回值'?你有什么不是转换的数字,它是*未定义的行为*因为'n'结束被使用而不被初始化 – UnholySheep

+0

'%d'当它变成非十进制字符时停止。 – stark

+1

好的,我把n初始化为0,然后输入一个没有返回的东西,这对我更有意义。谢谢UnholySheep – alexbourne98

回答

0

当你进入一个非小数字符使用%dscanf()返回0(错误),并没有设置n。当你打印它时,它是一个非初始化变量,然后打印随机值。

如果要对付这个问题,你可以得到用户的输入为string,检查它是否是一个正确的号码,然后将其转换为int

#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 
+1

详细信息:“除''-''外,使用'%d,scanf()'return 0”输入非十进制字符。 ''+'',tab,space,...'char str [10];'是没有足够空间来表示大的int值。基本的想法很好,但没有完成这项工作。 – chux

相关问题