[PAT]1001 A+B Format

思路:

1.将所求的值转为字符串,这里主要用到sprintf函数

2.从所求的字符串从低位开始转移到最终的结果字符串中,每个3位加一个','

坑点1:

-100000 9 结果为-999,991

如果不判断当前正在遍历的字符是否为‘-’,会得到:-,999,991

程序:

#include
#include

int main(){
	int  a, b;
	char result_temp[100], result[100];
	scanf("%d %d", &a, &b);
	sprintf(result_temp, "%d", a+b);
	int len = strlen(result_temp);
	int count = 0, j = 0;
	for(int i = len-1; i >= 0;){
		if(count == 3 && result_temp[i] != '-'){
			result[j++] = ',';
			count = 0;
		}else{
			result[j++] = result_temp[i];
			count++;
			i--;
		}
	}
	result[j] = '\0';
	for(int i = strlen(result)-1; i >= 0; i--){
		printf("%c", result[i]);
	}
	return 0;
} 


你可能感兴趣的:(PAT)