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

C语言输出指定范围符合条件数及求和时多余加号问题求助

问题描述

需要输出指定数值范围内能被16整除(注:原代码条件first%4==0 && first%16==0等价于被16整除,可简化)的数及其总和,例如范围15到85时,期望输出格式为「16 + 32 + 48 + 64 + 80 =240」。但当前代码运行后,最后一个数后会多出加号,输出为「16 + 32 + 48 + 64 + 80 + =240」,需要解决该格式问题。

当前使用的C语言代码:

#include <stdio.h>
#include <conio.h>
int main()
{
int first=0;
int second=0;
printf("Enter first number :");
scanf_s("%d",&first);
printf("Enter second number :");
scanf_s("%d",&second);
first++;
int sum=0;
while(first<=second)
{
    if(first%4==0 && first%16==0)
    {
        printf("%d  ",first);
        printf("+ ");
        sum+=first;
    }
    first++;
}
printf("  =%d ",sum);
}
解决方案

方法1:用标志位区分第一个符合条件的数

核心逻辑:第一个符合条件的数直接输出,后续的数先输出+ 再输出数字,从根源避免末尾多出加号。

修改后的代码:

#include <stdio.h>
#include <conio.h>
int main()
{
    int first=0;
    int second=0;
    printf("Enter first number :");
    scanf_s("%d",&first);
    printf("Enter second number :");
    scanf_s("%d",&second);
    first++;
    int sum=0;
    int is_first = 1; // 标记是否是第一个要输出的数
    while(first<=second)
    {
        if(first%16==0) // 简化原条件
        {
            if(is_first)
            {
                printf("%d",first); // 第一个数直接输出,不加前缀
                is_first = 0;
            }
            else
            {
                printf(" + %d",first); // 后续数先输出加号再输出数字
            }
            sum+=first;
        }
        first++;
    }
    printf(" = %d",sum);
    return 0;
}

方法2:先收集所有符合条件的数,再统一输出

如果数值范围不大,可以先把符合条件的数存入数组,之后遍历数组格式化输出:先输出第一个元素,后续每个元素前加+ ,最后输出总和。这种方法逻辑更清晰,也方便后续扩展功能。

示例代码:

#include <stdio.h>
#include <conio.h>
#define MAX_SIZE 100 // 根据实际范围调整数组大小
int main()
{
    int first=0;
    int second=0;
    printf("Enter first number :");
    scanf_s("%d",&first);
    printf("Enter second number :");
    scanf_s("%d",&second);
    first++;
    int sum=0;
    int nums[MAX_SIZE];
    int count = 0; // 记录符合条件的数的数量

    // 收集符合条件的数
    while(first<=second)
    {
        if(first%16==0)
        {
            nums[count++] = first;
            sum+=first;
        }
        first++;
    }

    // 格式化输出
    if(count > 0)
    {
        printf("%d", nums[0]);
        for(int i=1; i<count; i++)
        {
            printf(" + %d", nums[i]);
        }
    }
    printf(" = %d", sum);
    return 0;
}

内容的提问来源于stack exchange,提问作者M.Jafar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 16:27:23