C++甲级1001 A+B Format (20 分)(sprintf,memset,reverse)

本文详细解析了1001 A+B Format题目,介绍了如何计算两个整数的和,并按照标准格式输出结果,包括使用逗号分隔每三位数字的方法。提供了两种实现思路,一种是利用字符数组和字符串操作,另一种是使用栈实现。

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

1001 A+B Format (20 分)

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
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
 
int main()
{
    int a,b;
    while(scanf("%d%d",&a,&b)==2)
    {
        int c=a+b;
        char ans[9];//-1000000
        sprintf(ans,"%d",c);////把整数c 打印成一个字符串保存在ans中。头文件:cstdio 
        char res[10];//-1,000,000
        memset(res,0,sizeof(res));//将res中当前位置后面的sizeof(res)个字节 用 0 替换并返回 res ,相当于初试化res数组.头文件:cstring 
        int len=strlen(ans);
        int j=0;
        int cnt=0;
        for(int i=len-1;i>=0;i--)//因为输出是从后往前每三个数一个逗号,所以要借助数组res,逆序保存结果 ,再反转数组最后输出 
        {
            res[j++]=ans[i];
            cnt++;
            if(ans[i-1]>='0'&&ans[i-1]<='9' && cnt%3==0)
            {
                res[j++]=',';
            }
        }
        reverse(res,res+j);//reverse(res[0],res[j]) 可以将数组指针在[0,j)之间的元素范围内的元素进行反转 头文件:algorithm 
        printf("%s\n",res);
 
 
    }
    return 0;
}

F2:借助栈先进后出的特点 

#include<cstdio>
#include<stack>
using namespace std;
int main()
{
	int a,b,st;
	scanf("%d%d",&a,&b);
	st = a + b;
	int i = 0;
	if(st<1000 && st>-1000)//若为三位数则直接输出 
	{
		printf("%d\n",st);
		return 0;
	}

	if(st < 0)
	{
		printf("-");
		st=-st;
	}
	stack<int> sta;//建立一个栈,栈为先进后出 ,头文件<stack> 
	while(st>0)
	{
		i++;
		sta.push(st%10);//个位数依次进栈 
		st=st/10;
	}
	while(!sta.empty())
	{
		i--;
		printf("%d",sta.top());//输出栈顶元素 
		if(i!=0&&i%3==0)
			printf(",");
		sta.pop();//将栈顶元素删除 
 
	}
	printf("\n");
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值