PTA1001号题

PTA1001号题:

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).
PTA题库

1001 A+B Format

#include <stdio.h>
#include <string.h>
void fun(char *p, int remanider)//传入存有要转换格式数字的字符数组和字符数组长度对三取余的余数
{
    if (remanider != 0)//先输出余数位数后加逗号
    {
        for (int i = 0; i < remanider; i++)
        {
            printf("%c", p[i]);
        }
        printf(",");
    }
    int j = remanider;//继续输出
    for (int i = 1; i <= 3; i++)//每输出三位数输出一个逗号
    {
        printf("%c", p[j]);
        if (i == 3 && p[j + 1] != '\0')//到字符数组末时结束输出
        {
            printf(",");
            i = 0;
        }
        j++;
    }
}

int main(int argc, char const *argv[])
{
    int num1, num2;
    scanf("%d %d", &num1, &num2);
    num1 = num1 + num2;//先对num1和num2进行加减运算
    char a[30];//用于保存转换后的数字
    num2 = 0;
    if(num1 <1000&&num1>-1000)//如果计算后的数小于4位,直接输出
    {
        printf("%d",num1);
        return 0;
    }
    if (num1 < 0)//如果计算后的数是负数,先输出一个负号
    {
        printf("-");
        num1 *= -1;
    }
    do//将整数转换为字符型存入数组
    {
        a[num2] = (num1 % 10) + '0';//num1%10可以分离每个位数,分离出来的数+‘0’可转换为字符型存入数组
        num1 /= 10;//去掉分离的数,比如123将3分离,应该剩余12
        ++num2;
    } while (num1 != 0);
    int b = strlen(a) - 1;
    for (int i = 0; i < strlen(a) / 2; i++)//因为存入数组中的字符顺序是反的,因此要反转以下数组,从中间对半反转
    {
        int t = a[i];
        a[i] = a[b - i];
        a[b - i] = t;
    }
    fun(a, strlen(a) % 3);/*程序的关键函数,每输出三位输出一个‘,’,
                            用字符数长度对3取余,因为对于1234,我们要输出1,234,首次输出逗号时不能按三位输出
                            因此先输出对三取余的位数,比如1234的位数为4,对三取余为1,就先输出1位以后输出逗号
                            */
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值