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个数字
输入:
每个输入文件包含一个测试用例,每个测试用例包含一组整数a和b,a和b的范围都在-1,000,000,并且用空格分开
输出:
每个测试用例,应该在一行输出a和b的和,并且和一定要以标准形式输出
测试输入:
-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
}