(甲)1001 A+B Format (20 分)

本文解析了一道C++编程竞赛题目,要求计算两个整数的和并以标准格式输出,每三位用逗号分隔。文章提供了详细的解题思路和完整的代码实现,包括处理负数和正数的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

Calculate a+b and output the sum in standard format -- that is, the digits must be separated into groups of three by commas (unless there are less than four digits).

Input Specification:

Each input file contains one test case. Each case contains a pair of integers a and b where −10​6​​≤a,b≤10​6​​. The numbers are separated by a space.

Output Specification:

For each test case, you should output the sum of a and b in one line. The sum must be written in the standard format.

Sample Input:

-1000000 9

Sample Output:

-999,991

题意:

给你两个数字a,b,其中a,b的范围是 −10​^6​​≤a,b≤10​^6​​. 让你求出来a+b的结果,注意每三位要用一个“,”分隔。

思路:

把a+b的结果算出来,然后把结果拆分开,每三位加入一个分隔符“,”;最后注意正负号的输出和分隔符在首尾的位置不需要添加;

代码如下:

#include<stdio.h>
#include<string.h>
#include<string>
#include<math.h>
#include<iostream>
using namespace std;

int a,b;
string s;

int main()
{
    while(~scanf("%d%d",&a,&b))
    {
        int sum=a+b;//计算出来a+b的结果;
        if(sum==0)//注意,否则第四组测试数据会错;
            printf("0\n");
        else
        {
            s="";//清空字符串;
            int fu=0;//符号;
            if(sum<0)
                fu=1;//注意负号的输出;
            sum=fabs(sum);
            int k=0;
            while(sum!=0)//把数字拆分开存在字符串中,注意每三位加入一个“,”;
            {
                char tt=sum%10+'0';
                sum/=10;
                s=s+tt;
                k++;
                if(k==3)
                {
                    s=s+",";//加入“,”;
                    k=0;
                }
            }
            if(fu==1)//符号输出;
                cout<<"-";
            int l=s.size()-1;//注意下标是从0开始的;
            if(s[l]!=',')//注意第一位不用添加分隔符;
                cout<<s[l];
            for(int i=l-1; i>=0; i--)
            {
                cout<<s[i];
            }
            cout<<endl;
        }
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值