-
Notifications
You must be signed in to change notification settings - Fork 0
/
PAT-Basic-1054.cpp
105 lines (98 loc) · 2.43 KB
/
PAT-Basic-1054.cpp
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#include <iostream>
using namespace std;
/*bool isValid(string str){
if(str.find('.')!=string::npos){
if(str.find_last_of('.')!=str.find('.')) return false;
if(str.length()-str.find('.')-1 > 2) return false;
if(str.find('.')==str.length())
}
for(int i=0;i<str.length();i++){
if(!isdigit(str[i])){
if(!(str[i]=='-' && i==0) && !(str[i]=='.' && i>0 && i<str.length()-1)) return false;
}
}
double num=atof(str.c_str());
if(num>1000 || num<-1000) return false;
return true;
}*/
bool isValid(char* a){
char b[50];
double tmp;
sscanf(a,"%lf",&tmp);
sprintf(b,"%.2lf",tmp);
for(int i=0;i<strlen(a);i++){
if(a[i]!=b[i]) return false;
}
if(tmp>1000 || tmp<-1000) return false;
return true;
}
int main(){
int N;
cin>>N;
double sum=0,count=0;
for(int i=0;i<N;i++){
char a[50],b[50];
double tmp;
bool flag=true;
scanf("%s",a);
sscanf(a,"%lf",&tmp);
cout<<tmp<<endl;
sprintf(b,"%.2lf",tmp);
for(int i=0;i<strlen(a);i++){
if(a[i]!=b[i]) flag=false;
}
if(tmp>1000 || tmp<-1000) flag=false;
if(flag){
count++;
sum+=tmp;
}else{
cout<<"ERROR: "<<a<<" is not a legal number"<<endl;
}
}
// ×¢ÒânumberºÍnumbersµÄÇø±ð¡£¡£¡£
if(count>1)
printf("The average of %d numbers is %.2lf\n",count,(double)sum/count);
else if(count==1)
printf("The average of 1 number is %.2lf\n",sum);
else
printf("The average of 0 numbers is Undefined\n");
}
/*
#include <iostream>
using namespace std;
bool isValid(string str){
if(str.find('.')!=string::npos){
if(str.find_last_of('.')!=str.find('.')) return false;
if(str.length()-str.find('.')-1 > 2) return false;
}
int index=0;
if(str[0]=='-') index=1;
for(int i=0;i<str.length();i++){
if(!isdigit(str[i])){
if((str[i]!='.' && str[i]!='-') || (str[i]=='-' && i!=0) ) return false;
}
}
double num=atof(str.c_str());
if(num>1000 || num<-1000) return false;
return true;
}
int main(){
int N;
cin>>N;
double sum=0,count=0;
for(int i=0;i<N;i++){
string str;
cin>>str;
if(isValid(str)){
count++;
sum+=atof(str.c_str());
}else{
cout<<"ERROR: "<<str<<" is not a legal number"<<endl;
}
}
cout<<"The average of "<<count<<" numbers is ";
if(count==0) cout<<"Undefined"<<endl;
else if(count==1) printf("%.2lf",sum);
else printf("%.2lf",sum/double(count));
}
*/