PAT备考笔记—— A + B Format

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_39781267/article/details/81000970
    Calculate a + b and output the sum in standard format -- that is, thedigits must be separated into groups of three by commas (unless thereare less than four digits).
Input
    Each input file contains one test case. Each case contains a pair ofintegers a and b where -1000000 <= a, b <= 1000000. The numbersare separated by a space.
Output
    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   
解题思路一:该解题思路具有一定的针对性,是根据题目中给定的范围,分简单有限种情况进行讨论的,但是该方法不具有一定的普遍性,换了A,B的取值范围之后就不再使用。
#include <stdio.h>
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
int main(){
 int a, b;
int sum,c;
while (scanf("%d %d",&a,&b)!= EOF)
{  
    sum = a+b;  
    c = abs(sum);  
    if(c<1000)    
        printf("%d",sum);  
    else if(c>= 1000 && c< 1000000)    
        printf("%d,%03d",sum/1000,c%1000); 
    else if(c >= 1000000)    
        printf("%d,%03d,%03d",sum/1000000,(c%1000000)/1000,(c%1000000)%1000); }
     return 0;
}

解题思路二:这是一种比较普遍的解题的方法,使用范围较广泛。
#include <stdio.h>
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
// 格式化数据
string fun0(int s)
{
 string sumString = "";
 while (s / 1000)
 {
  string tempS = to_string(s);
  sumString = "," + tempS.substr(tempS.length() - 3, 3)+ sumString;
  s = s/1000;
 }
 string tempS = to_string(s);
 sumString = tempS + sumString;
 return sumString;
}
int main()
{
 int a, b;
 int sum;
 string result;
 cin >> a >> b;
 sum = a + b;
 result = fun0(sum); 
 printf("%s", result.c_str());
 return 0;
}

ps:打印字符串的时候,PAT官方的编辑器是要调.c_str();

展开阅读全文

没有更多推荐了,返回首页