【PAT】1001. A+B Format (20)-PAT甲级真题

因为没有在网上看到整理c++解法的,而我解题基本都是c++,所以分享上来....

不能保证效率 有更高效的方法非常欢迎评论私信等(持续更新)(欢迎正在一起刷题的小伙伴私信我一起讨论~)

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

digit:数字 commas:逗号

1、自解(c++)

符号:使用symbol记录符号,取绝对值。

逗号:用%1000取出后三位,用整数减去后三位再/1000得到前三位数

如果没有三位数以上,则不需要逗号

#include <iostream>
#include<iomanip>//如果后三位是0,需要用0填满
using namespace std;

void FormatA_B(int a, int b)
{
    int sum = a + b;
    char symbol = 0;
    if (sum < 0)symbol = '-';
    sum = abs(sum);//取绝对值
    int fir = sum % 1000;//记录后三位
    int sec = (sum -
     fir)/1000//如果小于三位数 就不需要逗号
    if(sec == 0)cout << symbol<<fir;
    else cout << symbol << sec << ',' <<setw(3)<<setfill('0')<< fir;
}

int main()
{
    int a, b;
    cin >> a>>b;
    FormatA_B(a, b);
}

【setw(3):填满三位;setfill('0'):用0填满】

2、c语言(对输出更方便:【用%03d来填满三个0】)

#include <iostream>
#include <stdio.h>
using namespace std;

void FormatA_B(int a, int b)
{
    int sum = a + b;
    char symbol = 0;
    if (sum < 0)symbol = '-';
    sum = abs(sum);//取绝对值
    int sec = sum % 1000;//记录后三位
    int fir = (sum - sec)/1000;//记录前三位

    //如果小于三位数 就不需要逗号
    if (fir == 0) { printf("%c", symbol); printf("%d", fir); }
    else { printf("%c", symbol); printf("%d,%03d", fir,sec); }
}

int main()
{
    int a, b;
    cin >> a>>b;
    FormatA_B(a, b);
}

3、柳神方法:将数字视作字符串输出:

#include <iostream>
#include <string>
using namespace std;
int main()
{
    int a, b;
    cin >> a>>b;
    string s = to_string(a + b);//转化成字符串形式
    int len = s.length();
    for (int i = 0; i < len; i++)
    {
        cout << s[i];
        if (s[i] == '-')continue;//如果有符号,就不进入if判断
        if ((i + 1) % 3 == len % 3 && (i + 1 != len))cout << ',';
    }
}

1、把数字以3位为一块,在((i+1) % 3 == len % 3)处有逗号。

2、continue作用:直接执行下一个循环判断,后面的语句全部不执行(无视负号的逗号判断)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值