学堂 学堂 学堂公众号手机端

1001 A+B Format (20 分)

lewis 1年前 (2024-04-18) 阅读数 19 #技术


1001A+B Format(20分)

Calculatea+band 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 integersaandbwhere−106≤a,b≤106. The numbers are separated by a space.


Output Specification:

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

Sample Input:
-1000000 9
Sample Output:
-999,991

初始版本:

#include<bits/stdc++.h>
using namespace std;
int main(){
//freopen("in.txt","r",stdin);
int a,b,c;
cin>>a>>b;
c=a+b;
char str[100];
sprintf(str,"%d",c);
string ans=str;
char res[100];
int k=0,count=0;
for(int i=ans.length()-1;i>=0;i--){
res[k++]=ans[i];
count++;
if(count%3==0&&(i-1>=0)&&(ans[i-1]!='-')) res[k++]=',';
}
for(int i=k-1;i>=0;i--){
cout<<res[i];
}
return 0;
}

改进版本

#include<bits/stdc++.h>
using namespace std;
int main() {
int a, b;
cin >> a >> b;
char ans[100];
sprintf(ans,"%d",a+b);
int len=strlen(ans);
for(int i=0;i<len;i++){
cout<<ans[i];
if(ans[i]!='-'&&(i!=len-1)&&(len-i-1)%3==0) cout<<",";//后面剩下3n个数时 要加','
}
return 0;
}

版权声明

本文仅代表作者观点,不代表博信信息网立场。

热门