PAT 1108

题目 : Finding Average

分值 : 20
难度 : 简单题
思路 : 按照题目要求,string读入判断是否是符合要求的字符.
坑点 : atoi atof to_string 了解一下

具体代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <iostream>
using namespace std ;
bool isdigital(string s)
{
int S = 0;
int count = 0 ;
if(s[0]=='-')S=1;
for(int i= S; i< s.size() ; i++ )
{
if(s[i]=='.' && s.size()-1-i>2)
return false ;
if(s[i]=='.'&& count)
return false ;
if(s[i]=='.')
count ++ ;
if(!isdigit(s[i])&& s[i]!='.')
return false ;
}
float temp = atof(s.c_str());
if(temp <-1000 || temp > 1000)
return false ;
return true ;
}

int main() {
int N ;
cin >> N ;
float sum = 0 ;
int Count = 0 ;
for(int i = 0 ; i <N ; i++)
{
string s;
cin >>s ;
if(!isdigital(s))
cout <<"ERROR: "<<s<<" is not a legal number" <<endl ;
else
{
sum += atof(s.c_str());
Count++ ;
}
}
if(Count>1)
printf("The average of %d numbers is %.2f\n" , Count,sum/Count) ;
else if(Count==1)
printf("The average of 1 number is %.2f\n" , Count,sum) ;
else
printf("The average of 0 numbers is Undefined\n");
//cout <<"The average of "<<Count<<" numbers is "<<sum<< endl ;

}