当前位置: 代码迷 >> 综合 >> PAT甲级题目1108 Finding Average
  详细解决方案

PAT甲级题目1108 Finding Average

热度:83   发布时间:2024-02-02 00:18:03.0

题目大意:
找出合法数字的个数和平均值

代码:

#include<bits/stdc++.h>
using namespace std;
double temp;
bool isnum(char str[])
{temp = 0;int size = strlen(str);bool point = false;int pointindex = 0;for(int i = 0; i < size; i++){if(str[i] == '-'){if(i == 0 )continue;}if(str[i] >= '0' && str[i] <= '9'){if(!point)temp = temp * 10 + str[i] - '0';elsetemp += (str[i] - '0') * pow(10, pointindex - i);}else if(str[i] == '.'){if(point)return false;pointindex = i;if(size - 1 - pointindex > 2)return false;point = true;}elsereturn false;}if(str[0] == '-')temp *= -1;if(temp <= 1000 && temp >= -1000)return true;return false;
}
int main()
{int n;scanf("%d", &n);char str[100];double sum = 0, num = 0;for(int i = 0; i < n; i++){scanf("%s", &str);if(isnum(str)){num++;sum += temp;}elseprintf("ERROR: %s is not a legal number\n", str);} if(num == 0)printf("The average of %d numbers is Undefined", int(num));else if(num == 1)printf("The average of %d number is %.2lf", int(num), sum);elseprintf("The average of %d numbers is %.2lf", int(num), sum / num);return 0;
}
  相关解决方案