The basic task is simple: given N real numbers, you are supposed to calculate their average. But what makes it complicated is that some of the input numbers might not be legal. A legal input is a real number in [−1000,1000] and is accurate up to no more than 2 decimal places. When you calculate the average, those illegal numbers must not be counted in.
Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (≤100). Then N numbers are given in the next line, separated by one space.
Output Specification:
For each illegal input number, print in a line ERROR: X is not a legal number where X is the input. Then finally print in a line the result: The average of K numbers is Y where K is the number of legal inputs and Y is their average, accurate to 2 decimal places. In case the average cannot be calculated, output Undefined instead of Y. In case K is only 1, output The average of 1 number is Y instead.
排除错误的情况之后,用atof将s.c_str()变为float再与 [−1000,1000]比较,合法则加入sum中。
#include<iostream>
using namespace std;
bool isNum(string s,float &f) {
int np = 0, pos = 0;
if ((s[0] < '0' || s[0]>'9') && s[0] != '-')return false;
for (int i=1; i < s.size(); i++) {
if (s[i] == '.') {
if (np == 0) {
np++;
pos = i;
}
else
return false;
}
else if (s[i] < '0' || s[i]>'9')return false;
}
if (np == 1 && s.size() - 1 - pos > 2)return false;
float temp = atof(s.c_str());
if (temp > 1000 || temp < -1000)return false;
f += temp;
return true;
}
int main() {
int n, cnt = 0;
string s;
float sum = 0;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> s;
if (!isNum(s, sum))printf("ERROR: %s is not a legal number\n", s.c_str());
else
cnt++;
}
if (cnt == 0)printf("The average of 0 numbers is Undefined\n");
else {
if (cnt == 1)printf("The average of %d number is %0.2f\n", cnt, sum / cnt);
else
printf("The average of %d numbers is %0.2f\n", cnt, sum / cnt);
}
return 0;
}
看了别人的,确实没有想到这样做,大佬就是大佬。
从输入字符串中提取出符合要求的float(用字符串存储),然后比较输入字符串与提取出的字符串,如果相等则说明输入字符串就是符合格式要求的,这时再判断一下是否在-1000~1000内就可以了。
原文:1108. Finding Average (20)-PAT甲级真题
#include <iostream>
#include <cstdio>
#include <string.h>
using namespace std;
int main() {
int n, cnt = 0;
char a[50], b[50];
double temp, sum = 0.0;
cin >> n;
for(int i = 0; i < n; i++) {
scanf("%s", a);
sscanf(a, "%lf", &temp);
sprintf(b, "%.2f",temp);
int flag = 0;
for(int j = 0; j < strlen(a); j++)
if(a[j] != b[j]) flag = 1;
if(flag || temp < -1000 || temp > 1000) {
printf("ERROR: %s is not a legal number\n", a);
continue;
} else {
sum += temp;
cnt++;
}
}
if(cnt == 1)
printf("The average of 1 number is %.2f", sum);
else if(cnt > 1)
printf("The average of %d numbers is %.2f", cnt, sum / cnt);
else
printf("The average of 0 numbers is Undefined");
return 0;
}