PAT-A 真题 – 1108 Finding Average

发布于 / PAT-甲级 / 0 条评论

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 Yis 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.

Sample Input 1:

7
5 -3.2 aaa 9999 2.3.4 7.123 2.35

Sample Output 1:

ERROR: aaa is not a legal number
ERROR: 9999 is not a legal number
ERROR: 2.3.4 is not a legal number
ERROR: 7.123 is not a legal number
The average of 3 numbers is 1.38

Sample Input 2:

2
aaa -9999

Sample Output 2:

ERROR: aaa is not a legal number
ERROR: -9999 is not a legal number
The average of 0 numbers is Undefined

题目大意:对于给定的n个数字,判断是不是合法的数字(合法首先得是数字,然后小数点后面最多两位)

将所有合法的数字求平均,然后输出有多少个合法 数字和他们的平均数。

注意输出中的number和numbers。

这道题使用C++的stod函数比较好写,注意部分版本的编译器没有这个函数。

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
const int maxn = 100;

double g_num = 16.9;  //存放字符串转数字结果 

bool Judge(char str[]){
  if(!strcmp(str, "-")) return false;  //只有一个负号,ban 
  int len = strlen(str), i = 0;
  int point_cnt = 0, numcnt = 0;  //point_cnt为小数点个数,numcnt为小数点后面的位数 
  if(str[0] == '-') i++;  //防止第一个符号被误判 
  for(; i < len; i++){
    if(point_cnt) numcnt++;  //如果出现过小数点,开始累计 
    if(str[i] == '.') point_cnt++;//如果是小数点,累计 
    if((str[i] > '9' || str[i] < '0') && str[i] != '.') return false;  //非数字,而且不是小数点 
    if(point_cnt > 1 || numcnt > 2) return false;   //出现一次以上小数点或小数点后位数超过2位 
  }
  g_num = stod(str);
  return g_num <= 1000 && g_num >= -1000; 
  return true;
}

int main(){
  int cnt, good_cnt = 0;
  double ans = 0;
  cin >> cnt;
  for(int i = 0; i < cnt; i++){
    char str[maxn];
    cin >> str;
    if(!Judge(str)){
      cout << "ERROR: " << str << " is not a legal number" << endl;  
    }else{
      good_cnt++;
      ans += g_num;
    }
  }
  if(good_cnt > 1) printf("The average of %d numbers is %.2f\n", good_cnt, ans / good_cnt);
  else if(good_cnt == 1)printf("The average of %d number is %.2f\n", good_cnt, ans / good_cnt);
  else printf("The average of 0 numbers is Undefined\n");
  return 0;
}

转载原创文章请注明,转载自: 斐斐のBlog » PAT-A 真题 – 1108 Finding Average
目前还没有评论,快来抢沙发吧~