本文主要是介绍NYIST 1092 数字分隔(二),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
本题是南阳理工学院ACM网站上的一道字符串处理题,很长时间不敲代码了手生得很,果然码了很长时间~
描述
在一个遥远的国家,银行为了更快更好的处理用户的订单,决定将一整串的数字按照一定的规则分隔开来,分隔规则如下:1、实数的整数部分按照每三个数字用逗号分隔开(整数部分的高位有多余的0时,需先将多余的0过滤后,再进行数字分隔,如:0001234567 输出结果为1,234,567.00)2、小数部分保留两位小数(四舍五入)3、如果该数是负的,则在输出时需用括号将分隔后的数字括起来,例如:-10005.1645的输出结果为(10,005.16)
输入
多组测试数据,每行输入一个实数n(n的位数小于100)
输出
输出分隔后的结果
样例输入
00012345670.0000-10005.1645
样例输出
1,234,567.000.00(10,005.16)
AC代码:
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <algorithm>
using namespace std;int main()
{char str[201], a[201];while(~scanf("%s", a)) {bool neg = false;int ten = 0;if(a[0] == '-') {neg = true;a[0] = '0';printf("(");}int len = strlen(a);int point = 0;for(int i = 0 ; i < len; ++i) {if(a[i] == '.') {point = i;break;}}
// printf("point = %d\n", point);if(point > 0) {//有小数前导零处理int i, j = 0;bool flg = true;for(i = 0; i < point-1; i++) {if(a[i] == '0' && flg) {continue;} else {str[j++] = a[i];flg = false;}}str[j++] = a[i];str[j++] = '.';for(i = point+1; i < len; i++) {str[j++] = a[i];}str[j] = '\0';} else {int j = 0;bool flg = true;for(int i = 0; i < len-1; i++) {if(a[i] == '0' && flg) {continue;} else {str[j++] = a[i];flg = false;}}str[j++] = a[len-1];str[j] = '\0';}
// printf("~~~%s~~~\n", str);len = strlen(str);point = 0;for(int i = 0 ; i < len; ++i) {if(str[i] == '.') {point = i;if(i == len-1) {str[len] = str[len+1] = '0';str[len+2] = '\0';} else if(i == len-2) {str[len] = '0';str[len+1] = '\0';} else if(len-point-1 > 2) {if(str[point+3] >= '5' && str[point+3] <= '9') {if(str[point+2] != '9') {str[point+2] += 1;} else {char c = str[0];for(int t = point+2; t >= 0; t--) {if(str[t] == '.') {continue;}if(str[t] == '9') {str[t] = '0';} else {str[t] += 1;break;}}if((c == '9' && str[0] == '0')) {ten = 1;}}}str[i+3] = '\0';} else {str[i+3] = '\0';}}}if(ten) {printf("1");if(point%3 == 0) {printf(",");}}if(point > 0) {//有小数if(point <= 3) {printf("%s", str);} else {int i;int head = point%3;int cnt = 0;;for(i = 0; i < head; i++) {printf("%c", str[i]);cnt = 3;}// printf("-!%d %d!-\n", cnt, i);for( ; i < point; i++) {if(cnt == 3) {cnt = 0;printf(",");}printf("%c", str[i]);cnt++;}if(point > 0) {printf(".");}printf("%c%c", str[point+1], str[point+2]);}} else {//整数int i, head = len%3;int cnt = 0;;for(i = 0; i < head; i++) {printf("%c", str[i]);cnt = 3;}for( ; i < len; i++) {if(cnt == 3) {cnt = 0;printf(",");}printf("%c", str[i]);cnt++;}printf(".00");}if(neg) {printf(")");}printf("\n");}return 0;
}
测试样例:
999999999.999999
-999999999.999999
这篇关于NYIST 1092 数字分隔(二)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!