【算法笔记】B1054 求平均值

时间:2022-09-23 20:26:24
atof(str)字符串转换浮点数
 #include<bits/stdc++.h>
using namespace std;
bool isLegal(char *s){
int i = ;
if(s[]=='-'){
i++;
}
for(;s[i]&&s[i]!='.';i++){
if(!isdigit(s[i])){
return false;
}
}
if(s[i]=='.'){
for(int j=i+;s[j];j++){
if(!isdigit(s[j])||j-i>){
return false;
}
}
}
double a = fabs(atof(s));
if(a>1000.0){
return false;
}
return true;
}
int main(){
int n,nums = ;
double sum;
char *x;
x=(char *)malloc(sizeof(char));
cin>>n;
for(int i = ; i < n; i++){
scanf("%s", x);
if(isLegal(x)){
nums++;
sum += atof(x);
}else{
printf("ERROR: %s is not a legal number\n", x);
}
}
if(nums){
if(nums==){
printf("The average of 1 number is %.2lf\n",sum);
}else{
printf("The average of %d numbers is %.2lf\n",nums,sum/nums);
}
}else{
printf("The average of 0 numbers is Undefined\n");
}
return ;
}