PAT: A + B Format

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 并以标准的形式输出和,标准形式即:每3个数字以逗号分隔,除非和不足4个数字

输入:

每个输入文件包含一个测试用例,每个测试用例包含一组整数abab的范围都在-1,000,000,并且用空格分开

输出:

每个测试用例,应该在一行输出ab的和,并且和一定要以标准形式输出

测试输入:

-1000000 9

测试输出:

-999,991

代码:花了一天半调试,也是醉了,还得快快成长

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>

char num_to_char(int a)
{
    return '0'+(a-0);
}

void my_ltoa(long num_arg, char *num_str)//
{
    long num = 0;
    if(num_arg < 0){
        num = -num_arg;
    }else{
        num = num_arg;
    }

    char str[20] = "";//clear space of variate str
    int i = 0;
    int j = 0;
    while(num/10){
        int tmp = num%10;
        char tmp_char = num_to_char(tmp);
        str[i] = tmp_char;
        i++;
        if((i-j)%3 == 0){// for comma
            str[i] = ',';
            i++;
            j++;
        }
        num = num/10;
    }
    str[i] = num_to_char(num%10);
    if(num_arg < 0){
        str[++i] = '-';
    }
    // inverse str
    int str_len = strlen(str);
    i = 0;
    while(i < str_len/2){ // not <=
        char tmp = str[i];
        str[i] = str[str_len-1-i];
        str[str_len-1-i] = tmp;
        i++;
    }

    assert(num_str != NULL);
    char *r = (char *)str;
    while(*r != '\0'){
        *num_str = *r;
        r++;
        num_str++;
    }
    *num_str = '\0';// '\0' is the final character of a string, means the end of a string
}

int main()
{
    long a,b;
    scanf("%ld %ld",&a,&b);
    if(a<-1000000 || a>1000000 || b<-1000000 || b>1000000){
        return -1;
    }
    long sum = a + b;
    char sum_str[20];// as the arg of function my_ltoa,wrong sta: char *sum_str,
    my_ltoa(sum,sum_str);// sum_str must be allocated space
    printf("%s\n",sum_str);

}


完成这个代码主要遇到的问题 就是 字符串的传参与返回问题:

通过参考csdn上相关前辈的讲解,我选择的方法是strcpy和strcat的思路,即:

将字符串指针作为函数参数传入,并返回该指针。

char *strcpy(char *des,const char *source)// des在被调用的原函数中必须分配过空间,不能只是单纯的一个指针
{ 
    assert((des != NULL) && (source != NULL));
    char *r = des;// copy des pointer to a new variate

    while(*source != '\0'){
        *r = *source;
        r++;
        source++;
    }
    *r = '\0';// '\0' is the final character of a string, means the end of a string

    return r;// return r
}


 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值