题目链接:1108 Finding Average (20分)
题意:
给出N个字符串,找出[-1000,1000]内的不超过两位小数的数。
题解
可以使用sscanf(str, “%lf”, t); 将str以double型赋值给t,
然后在将sprintf(a, “%.2f”, t); 在将t以两位小数的形式赋值给字符数组a
逐一比较str,a各个位上是否相等,不等则不满足题意。
代码1
#include <iostream>
#include <cstring>
#include <cstdio>
#include <string>
#include <cctype>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;
const int ERROR = -88888;
const int maxn = 100;
int change(char s[]);
int main(int argc, char** argv) {
int n;
scanf("%d", &n);
getchar();
char s[maxn];
int ant = 0;
double t, sum;
for(int j = 0; j < n; j++) {
scanf("%s", s);
char a[maxn];
sscanf(s, "%lf", &t);
sprintf(a, "%.2f", t);
double res = t;
if (strlen(s) > strlen(a) || t > 1000 || t < -1000) {
res = ERROR;
} else {
for (int i = 0; i < strlen(s); i++)
if (s[i] != a[i]) {
res = ERROR;
break;
}
}
if (res == ERROR) {
printf("ERROR: %s is not a legal number\n", s);
} else {
ant++;
sum += res;
}
}
if (ant == 0)
printf("The average of 0 numbers is Undefined\n");
else if (ant == 1)
printf("The average of 1 number is %.2f\n", sum);
else
printf("The average of %d numbers is %.2f", ant, sum / ant);
return 0;
}
代码2
#include <iostream>
#include <cstring>
#include <cstdio>
#include <string>
#include <cctype>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;
const int ERROR = -88888;
const int maxn = 1000;
double change(char s[]);
int main(int argc, char** argv) {
int n;
scanf("%d", &n);
getchar();
char s[maxn];
int ant = 0;
double sum = 0;
while(n--) {
scanf("%s", s);
double res = change(s);
if (res == ERROR) {
printf("ERROR: %s is not a legal number\n", s);
} else {
ant++;
sum += res;
}
}
if (ant == 0)
printf("The average of 0 numbers is Undefined\n");
else if (ant == 1)
printf("The average of 1 number is %.2f\n", sum);
else
printf("The average of %d numbers is %.2f", ant, sum / ant);
return 0;
}
double change(char s[]) {
int len = strlen(s);
int begin = 0, i;
if (s[0] == '-') {
begin = 1;
}
double sum = 0;
for (i = begin; i < len; i++) { // 到第一个小数点停。
if (s[i] == '.')
break;
if (!isdigit(s[i]))
return ERROR;
sum = sum * 10 + s[i] - '0';
}
if (len - i - 1 > 2) // 小数位大于2
return ERROR;
double sum2 = 0;
for (i++; i < len; i++) {
if (!isdigit(s[i]))
return ERROR;
sum2 = sum2 * 10 + s[i] - '0';
}
sum2 = sum2 >= 10 ? sum2 / 100 : sum2 / 10;
sum = sum + sum2;
if (sum >= -1000 && sum <= 1000)
return begin == 1 ? -sum : sum;
else
return ERROR;
}