1001 A+B Format
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:
1 | -1000000 9 |
Sample Output:
1 | -999,991 |
思路:
当输出多行数值时,一定要注意是否有多余或缺少空行的情况
将 int 转换为 string 可以直接使用 to_string(x)
使用string 代替char数组的好处是 可以使用string自带的函数简化代码,提高效率。
代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | #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; } |
简化代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | #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; } |
分类:
PTA甲级
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 按钮权限的设计及实现