You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言斐波那契数列程序输入无响应与死循环问题求解

C语言斐波那契实现问题排查与修复

问题1:首次输入数值后无输出,需重复输入才能正常打印

触发原因

  • 原代码存在重复读取输入的逻辑:程序先调用get_int()读取了用户第一次输入的数值并赋值给n,随后while循环的判断条件中又执行了一次scanf("%d", &n),相当于第一次输入的内容被get_int()直接消费,循环会阻塞等待第二次输入,因此需要输入两次才能触发输出。

修复思路

删除while循环条件中重复的scanf调用,调整为每次输出完成后重新读取下一轮的输入即可。

问题2:修改后程序进入无限循环持续输出

触发原因

  • 调整后的代码while循环仅判断n > 0,但整个循环体内没有任何更新n值的逻辑:第一次输入的n是正数时,循环条件永久成立,程序会反复打印对应长度的斐波那契数列,永远不会退出。

修复方案

在每轮循环输出完数列后,新增调用get_int()读取新的输入值更新n,让循环条件可以正常判断是否终止。


修复后完整代码

//F(0) = 0,F(1) = 1, F(n) = F(n - 1) + F(n - 2)(n >= 2,n∈N*)
#include <stdio.h>
int Fibonacci(int n);
int get_int(void);
int main(void)
{
    int n, i;
    printf("Please enter the No. (<0 to quit) :\n");
    n = get_int();
    while (n > 0)
    {
        for (i = 1; i <= n; i++)
        {
            printf("%d ", Fibonacci(i));
        }
        printf("\n");
        // 读取下一轮输入,更新n的值
        printf("Please enter the No. (<0 to quit) :\n");
        n = get_int();
    }
    printf("Done.\n");
    return 0;
}
int Fibonacci(int n)
{
    if (n == 1)
    {
        return 0;
    }
    else if (n == 2)
    {
        return 1;
    }
    else if (n >= 3)
    {
        return Fibonacci(n - 1) + Fibonacci(n - 2);
    }
    // 补充边界返回值,避免传入非法参数时出现未定义行为
    return 0;
}
int get_int(void)
{
    int x;
    while ((scanf("%d", &x)) != 1)
    {
        scanf("%*s");  
        printf("Please enter an integer number(>0):\n");
    }
    while (getchar() != '\n')
        continue;  
    return x;
}

内容的提问来源于stack exchange,提问作者Algo-Goer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 00:36:01