南阳1092----数字分隔(二)

 1 #include <cstdio>
 2 #include <cstring>
 3 #include <iostream>
 4 using namespace std;
 5 char s[105];
 6 int main(){
 7     bool is_native;
 8     int len, point, endline;
 9     while(~scanf("%[^\n]",s)){
10         getchar();//吃回车
11         if(s[0] == '-') is_native = true;//判断负数
12         else is_native = false;
13         point = len = strlen(s);//当没有小数点时,len处为小数点
14         for(int i = 0; s[i]; ++i)//找小数点
15             if(s[i] == '.'){
16                 point = i;
17                 break;
18             }
19         endline = point;//.999
20         if(point-1 >= 0 && s[point-1] >= '0' && s[point-1] <= '9')//0.999
21             endline = point-1;
22         for(int i = 0; i < point; ++i)//00000123
23             if(s[i] > '0' && s[i] <= '9'){
24                 endline = i;
25                 break;
26             }
27         s[point] = '.';//len处可能没有.
28         for(int i = point+1; i <= point+3; ++i)//处理小数点后三位
29             s[i] = s[i]?:'0';
30         if(s[point+3] > '4') ++s[point+2];//小数点后第二位的进位
31         int up = s[point+3] = 0;
32         for(int i = point+2; i >= endline; --i){//依次进位
33             if(i == point) continue;
34             s[i] += up;
35             up = (s[i]-'0')/10;
36             s[i] = (s[i]-'0')%10 + '0';
37         }
38         bool is_all_zero = true;//0000000.0之类的
39         for(int i = point-1; i >= endline; --i)
40             if(s[i] != '0') is_all_zero = false;
41         if(up) is_all_zero = false;//0.999
42         int num = (point+2)%3;//找出在那加入,
43         if(is_native) putchar('(');
44         if(up){
45             printf("%d",up);
46             if(s[0] != '.' && (endline+2)%3 == num)
47                 putchar(',');
48         }
49         int i;
50         if(is_all_zero) { putchar('0'); i = point; }//前面都是零输出一个零,并从小数点处开始继续输出
51         else i = endline;//否则从开头开始
52         for(; i < point+3; ++i){
53             putchar(s[i]);
54             if(i < point-1 && i%3 == num)
55                 putchar(',');
56         }
57         if(is_native) putchar(')');
58         putchar('\n');
59         memset(s,0,sizeof(s));//清空数组,防止干扰
60     }
61     return 0;
62 }

 

posted @ 2018-04-17 09:47  Posase  阅读(209)  评论(0编辑  收藏  举报