2017-10-08 20 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

相關問題