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

为什么C语言用while循环打印偶数时输出是输入上限的两倍

问题原因
  • 你的代码逻辑是通过a*2生成偶数,循环条件设置为a <= 输入的Go值,当你输入Go=20时,a会从0遍历到20,对应生成的偶数就是0到40,因此输出最大值为输入值的两倍。
  • 代码额外输出了不符合需求的0,且末尾没有换行,导致shell提示符%直接拼接在输出内容末尾。
修复代码

如果要实现「输入上限值,打印1到该上限之间的所有偶数」,可以参考以下修改后的代码:

#include<stdio.h>

int main()
{
    int current = 1, upper;
    printf("Enter the Value:\n");
    scanf("%d", &upper);
    while(current <= upper) {
        if (current % 2 == 0) {
            printf("%d\t", current);
        }
        current++;
    }
    printf("\n");
    return 0;
}

如果要保留原代码中用乘法生成偶数的写法,调整循环条件即可:

#include<stdio.h>

int main()
{
    int a = 1, even, upper;
    printf("Enter the Value:\n");
    scanf("%d", &upper);
    while(a * 2 <= upper) {
        even = a * 2;
        printf("%d\t", even);
        a++;
    }
    printf("\n");
    return 0;
}

内容的提问来源于stack exchange,提问作者Vyomanaut

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 22:36:08