PAT 0001

2 篇文章 0 订阅

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≤106
​​ . 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 1
Sample Output:
-999,991
#include<bits/stdc++.h>
using namespace std;
int main(){
	long int op1,op2;
	long int sum;
	cin>>op1>>op2;
	sum=op1+op2;
    if(sum<0){
    	cout<<"-";
		sum=abs(sum); 
	}
	if(sum==0) cout<<0;
    char buf[10]="";
    sprintf(buf, "%ld", sum);
    int len=strlen(buf);
	int m=len/3;
	int n=len%3;
	int start=0;
	if(n==0){
		cout<<buf[0]<<buf[1]<<buf[2];
		start=3;
		m=m-1;
	}
	else if(n==1){
		cout<<buf[0];
		start=1;
	}
	else if(n==2){
		cout<<buf[0]<<buf[1];
		start=2;
	}
    while(m!=0){
		cout<<",";
		cout<<buf[start]<<buf[start+1]<<buf[start+2];
		start+=3;
		m--;
	}    
	return 0;
} 

注意点:
1.数值型数据转换为字符数组有现成函数可调用:
例1: itoa(sum,buf,10);//将数值转换成为字符数组的形式;
但是这条函数在浙大PAT练习系统里面没有,无法通过;
例2: sprintf(buf, “%ld”, sum); 这个就OK.
备注两条:
// 数字转字符串
sprintf(str, “%d”, num);
// 字符串转数字
sscanf(str, “%d”, &rsl);
2.要体会一下这种输出方式的内在逻辑:
本次的思路是分组输出,三个一组,不够的单独输出;
3.还有这一题过检测点的问题,一直是19分
终于找到原因是我直接if(sum==0) cout<<0;
把这条语句去掉之后就OK,输出零的位数会有差别。
但我仍然挺迷这题目也没规定0是怎么处理的哇?
找了好久终于找到,
如果各位大神朋友有什么高见,欢迎评论区讨论!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值