1054 求平均值 (20 分)
题目链接
算法分析
关键就在于判断是否合法,应当注意以下几点:
①.小数点的数目。
②.小数点后数字个数
③.该数的绝对值大小是否大于1000
其次就是统计合法数字的个数,然后再进行特殊判断,分以下三种情况:
①.0个合法数字
②.1个合法数字
③.2个及以上个合法数字
总结
字符串与数字之间的转化常用的库函数及其头文件
1.字符串到数字(#include<stdlib.h>)
atof(将字符串转换成浮点型数)
atoi(将字符串转换成整型数)
atol(将字符串转换成长整型数)
2.数字到字符串(#include<stdio.h>)
sprintf(用法就是在printf的第一个参数前面加上字符串首地址就好了)
代码实现
#include<bits/stdc++.h>
using namespace std;
#define N 10
char s[N];
double sum;//合法数字的总和
int sum_cnt;//合法数字的个数
int main(){
int n;
scanf("%d", &n);
for(int i = 1; i <= n; ++ i){
scanf("%s", s);
int len = strlen(s);
int cnt = 0, num = 0;//cnt统计小数点个数。num统计第一个小数点后数字的个数
bool flag = 0;//是否出现小数点
for(int j = 0; j < len; ++ j){
if(isdigit(s[j])){
if(flag) num ++;//如果已经出现小数点,则开始统计小数点后数字的个数
continue;
}
else if(s[j] == '.'){
flag = 1;
cnt ++;
}
else if(s[j] == '-')
continue;
else{
cnt = 100;//非法字符,把cnt设定为一个极大值
break;
}
}
double x = atof(s);
if(fabs(x) > 1000 || cnt >= 2 || num > 2){//非法的情况
printf("ERROR: %s is not a legal number\n", s);
continue;
}
else{
sum += x;
sum_cnt ++;
}
}
if(!sum_cnt)
printf("The average of 0 numbers is Undefined");
else if(sum_cnt == 1)
printf("The average of 1 number is %.2f", sum / sum_cnt);
else
printf("The average of %d numbers is %.2f", sum_cnt, sum / sum_cnt);
return 0;
}