1001 A+B Format
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 −106≤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 9
Sample Output:
-999,991
思路:
当输出多行数值时,一定要注意是否有多余或缺少空行的情况
将 int 转换为 string 可以直接使用 to_string(x)
使用string 代替char数组的好处是 可以使用string自带的函数简化代码,提高效率。
代码:
#include<stdio.h> #include<string.h> #include<iostream> using namespace std; int main(){ int a,b,sum,t=0,l; char s[100]; while(scanf("%d%d",&a,&b) != -1){ sum = a + b; sprintf(s, "%d", sum); if(s[0] == '-'){ if(strlen(s) < 5){ cout<<s; }else{ cout<<s[0]; l = strlen(s) - 1; for(int i=1; i<=l % 3; i++){ cout<<s[i]; } if(l % 3 != 0) cout<<","; t = 0; for(int i=l % 3 + 1; i < strlen(s); i++){ cout<<s[i]; t++; if(t == 3 && i != strlen(s) - 1){ cout<<","; t = 0; } } } } else{ if(strlen(s) < 4){ cout<<s; }else{ l = strlen(s); for(int i=0; i<l % 3; i++){ cout<<s[i]; } if(l % 3 != 0) cout<<","; t = 0; for(int i=l % 3; i < strlen(s); i++){ cout<<s[i]; t++; if(t == 3 && i != strlen(s) - 1){ cout<<","; t = 0; } } } } cout<<endl; } return 0; }
简化代码:
#include <iostream> using namespace std; int main() { int a, b; cin >> a >> b; //输入a和b string s = to_string(a + b); //将a+b的值转换为字符串 if(s[0] == '-') { //处理符号 cout << '-'; s.erase(0, 1); } int count = 0; //用于记录当前位置 for(int i = s.length() - 1; i >= 0; i--){ //添加逗号 count++; if(count % 3 == 0 && i > 0){ s.insert(i, ","); } } cout << s; }
标签:string,Format,int,sum,include,1001,cout From: https://www.cnblogs.com/yccy/p/16883770.html