atof(str)字符串转换浮点数
1 #include<bits/stdc++.h>
2 using namespace std;
3 bool isLegal(char *s){
4 int i = 0;
5 if(s[0]=='-'){
6 i++;
7 }
8 for(;s[i]&&s[i]!='.';i++){
9 if(!isdigit(s[i])){
10 return false;
11 }
12 }
13 if(s[i]=='.'){
14 for(int j=i+1;s[j];j++){
15 if(!isdigit(s[j])||j-i>2){
16 return false;
17 }
18 }
19 }
20 double a = fabs(atof(s));
21 if(a>1000.0){
22 return false;
23 }
24 return true;
25 }
26 int main(){
27 int n,nums = 0;
28 double sum;
29 char *x;
30 x=(char *)malloc(sizeof(char));
31 cin>>n;
32 for(int i = 0; i < n; i++){
33 scanf("%s", x);
34 if(isLegal(x)){
35 nums++;
36 sum += atof(x);
37 }else{
38 printf("ERROR: %s is not a legal number
", x);
39 }
40 }
41 if(nums){
42 if(nums==1){
43 printf("The average of 1 number is %.2lf
",sum);
44 }else{
45 printf("The average of %d numbers is %.2lf
",nums,sum/nums);
46 }
47 }else{
48 printf("The average of 0 numbers is Undefined
");
49 }
50 return 0;
51 }