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

C语言循环逻辑异常:程序未按预期在100终止循环求助

循环终止条件错误导致输出到150而非100

你的问题出在循环条件判断对象错误:

  • 你用i<=100作为终止条件,但i是从0开始的循环计数器,这会让循环执行101次(i从0到100)。
  • n初始值为50,每次循环加1,执行101次后n会变成50+101-1=150,所以最终输出停在150。

修复方案(二选一)

方案1:直接基于目标变量n判断终止条件(推荐,去掉多余的i)

删除无用的i变量,让循环在n达到100时停止:

#include<stdio.h>

int main()
{
    int n=50;
    printf("Number\tSquare\tCube\n");
    printf("____________________________\n");

    while (n <= 100)
    {
        printf("%d\t%d\t%d\n", n, n * n, n * n * n);
        n++;
    }
    return 0;
}

方案2:保留i,调整循环次数

从50到100共有51个数字(100-50+1),所以循环次数应设为51次:

#include<stdio.h>

int main()
{
    int n=50;
    int i=0;
    printf("Number\tSquare\tCube\n");
    printf("____________________________\n");

    while (i < 51)
    {
        printf("%d\t%d\t%d\n", n, n * n, n * n * n);
        i++;
        n++;
    }
    return 0;
}

额外提示

conio.h是老旧的DOS平台头文件,现代编译器(如GCC、Clang)大多不支持,建议删除该头文件,只保留必要的stdio.h即可。

内容的提问来源于stack exchange,提问作者ginger ale and whiskey

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 19:05:22