我写了一个程序返回斐波纳契数列的第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