Pat-甲级真题——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

Each input file contains one test case. Each case contains a pair of integers a and b where -1000000 <= a, b <= 1000000. The numbers are 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和输出和标准格式——也就是说,必须分为三组数字由逗号分隔(除非有少于四位数)。

输入

每个输入文件包含一个测试用例。每个案件包含两个整数a和b,-1000000 < = a、b < = -1000000。这些数字用空格分隔。

输出

为每个测试用例,你应该输出a和b在一行的总和。之和必须用标准的格式。

样例输入
-1000000 9
样例输出
-999,991












源代码:


#include <iostream>
using namespace std;
void Print(long s,bool sig){
        int count1 = 1,count2 = 0;
        bool siga = sig;
        long sum = s;
        long su[10] ;
        char signal[3];
       //如果和为0
        if(sum == 0) {
cout<<'0';
}


else{
//如果结果为正
        if(siga == true) {


while(sum != 0) {
su[count1] = sum % 10;
sum/=10;
count1++;
if((count1-1)%3 ==0 ) {
count2++;
signal[count2] = ',';
}
}


if(count1 >= count2*3) {
for(int i=count1-1;i>0;i--) {
                        cout<<su[i];
if((i-1)%3 == 0 && i>3) {
if(signal[count2]!=0) {
cout<<signal[count2];
count2--;
}
}
}
}
else {
for(int i=count1-1;i>0;i--) {
cout<<su[i];
}
}
}


//结果为负
else {
while(sum != 0) {
su[count1] = sum % 10;
sum/=10;
count1++;
if((count1 - 1)%3 ==0 ) {
count2++;
signal[count2] = ',';
}
}
cout<<'-';
if(count1 >= count2*3) {
for(int i=count1-1;i>0;i--) {
cout<<su[i];
if((i-1)%3 == 0 &&i>3) {
if(signal[count2]!=0) {
cout<<signal[count2];
count2--;
}
}
}
}
else {
for(int i=count1-1;i>0;i--) {
cout<<su[i];
}
}




}
}
}


int main(){
    long a,b,sum = 0;
bool si = true;
cin>>a>>b;
if((1000000>=a) && (a>=-1000000) && (1000000>=b) && (b>=-1000000)) {
sum = a + b;
if(sum < 0) {
sum = ~sum +1 ;
si = false;
Print(sum, si);
}
else Print(sum, si);
}
return 0;

}


思路:很显然7位带符号数可以用long定义变量,这个难点不在计算出和,而是对于算出的和,该如何将其每隔3位输出,

开始思路为循环,然后发现三次循环后插入','有点复杂,选择用数组,一个数组存数,一个存符号,当把逻辑全部理清后

这些循环(注意为什么有时候要先输出再进行自加,有时候又先自加再输出,对应的判断语句又是如何使用的)的结构就

清楚了,代码自然就出来了。


ps:可以看看大神们的代码,写的真的简洁

https://www.liuchuo.net/archives/1888

猜你喜欢

转载自blog.csdn.net/jack_zj123/article/details/80028521
今日推荐