问题链接:UVA11945 Financial Management。
题意简述:输入12个数,计算其平均值。
编写程序时,考虑到C++处理输入比较方便,所以使用C++语言编程。然而,输出稍微麻烦一些,对于金额,每3位需要加一个逗号,而C和C++的函数库中,没有相应的解决办法。
程序中专门编写函数output_result()处理输出,使用的是有限状态自动机的工作方式来处理的。
这个问题与UVALive2362 POJ1004 HDU1064 ZOJ1048 Financial Management基本上相同,只是输入输出数据格式略有不同。
AC的C语言程序如下:
/* UVA11945 Financial Management */
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
void output_result(char s[], char t[])
{
int len = strlen(s);
int i = len - 1, j=0;
int state = 0, count;
while(i >=0) {
count++;
t[j++] = s[i];
if(s[i] == '.') {
state = 1;
count = 0;
} else if(s[i] == '$')
state = 2;
if(state == 1 && count == 3 && s[i-1] != '$')
t[j++] = ',';
i--;
}
j--;
while(j >= 0)
putchar(t[j--]);
}
int main()
{
int t2;
double val, sum;
char s[128], t[128];
cin >> t2;
for(int i=1; i<=t2; i++) {
sum = 0;
for(int j=1; j<=12; j++) {
cin >> val;
sum += val;
}
sprintf(s, "%d $%.2f\n", i, sum / 12);
output_result(s, t);
}
return 0;
}