我寫了一個程序返回斐波納契數列的第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);
}
}
}
}
你是否檢查'scanf函數的返回值'?你有什麼不是轉換的數字,它是*未定義的行爲*因爲'n'結束被使用而不被初始化 – UnholySheep
'%d'當它變成非十進制字符時停止。 – stark
好的,我把n初始化爲0,然後輸入一個沒有返回的東西,這對我更有意義。謝謝UnholySheep – alexbourne98