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 Specification:
Each input file contains one test case. Each case contains a pair of integers a and b where −10
6
≤a,b≤10
6
. The numbers are separated by a space.
Output Specification:
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
分析:我的思路一开始其实是转换字符串,然后发现不会把sum给转成字符串(其实只要把sum一个个分开存入字符串数组就好了呀!!) 然后网上思路也行,就是:先算出Sum,然后按位输出,区分正负0,三位一逗号再加条件判断即可
其中注意:取绝对值函数fabs(),里面的参数需要是float int取值范围2^31 -1 = 2147483647
C语言中int的取值范围为:-2147483648 ~ 2147483647 一共有10位呢!所以直接用Int存储就可以
记录一个问题:
#include <stdio.h>
#include <math.h>
int main()
{
int a,b,sum=0,i=0,j,t=0;
int number[100000];
scanf("%d %d",&a,&b);
sum=a+b;printf("%d “,sum);
if(sum<0) {printf(”-"); sum=-sum;printf("%d “,sum);}
else if(sum=0) {sum=0;printf(”%d “,sum);}
else {printf(”%d ",sum);}
为什么这种结构a=100 b=300输出的sum是0?
#include <stdio.h>
int main()
{
int a,b,sum=0,i=0,j;
int number[100000];
scanf("%d %d",&a,&b);
sum=a+b;
if(sum<0) {printf("-"); sum=-sum;printf("%d “,sum);}
else if(sum>0) sum=sum;
else sum=0;
while(sum>0)
{
number[i++]=sum%10;
sum/=10;
}
for(j=i-1;j>=0;j–)
{
if(j%3==0&&j!=0) printf(”,");
printf("%d",number[j]);
}
return 0;
}
这种做法也不对
但这种做法就可以:
#include<stdio.h>
#include<math.h>
int main(){
int a, b, sum;
int i = 0, j;
int flag[10];
scanf("%d %d", &a, &b);
sum = a + b;
if(sum < 0)
printf("-");
int num = fabs((float)sum);
if(num == 0)
printf(“0”);
else{
while(num > 0){
flag[i++] = num % 10;
num /= 10;
}
for(j = i-1; j >=0; j–){
printf("%d", flag[j]);
if(j % 3 == 0 && j != 0)
printf(",");
}
}
return 0;
}