1054. 求平均值 (20)
本题的基本要求非常简单:给定N个实数,计算它们的平均值。但复杂的是有些输入数据可能是非法的。一个“合法”的输入是[-1000,1000]区间内的实数,并且最多精确到小数点后2位。当你计算平均值的时候,不能把那些非法的数据算在内。
输入格式:
输入第一行给出正整数N(<=100)。随后一行给出N个实数,数字间以一个空格分隔。
输出格式:
对每个非法输入,在一行中输出“ERROR: X is not a legal number”,其中X是输入。最后在一行中输出结果:“The average of K numbers is Y”,其中K是合法输入的个数,Y是它们的平均值,精确到小数点后2位。如果平均值无法计算,则用“Undefined”替换Y。如果K为1,则输出“The average of 1 number is Y”。
输入样例1:
7
5 -3.2 aaa 9999 2.3.4 7.123 2.35
输出样例1:
ERROR: aaa is not a legal number
ERROR: 9999 is not a legal number
ERROR: 2.3.4 is not a legal number
ERROR: 7.123 is not a legal number
The average of 3 numbers is 1.38
输入样例2:
2
aaa -9999
输出样例2:
ERROR: aaa is not a legal number
ERROR: -9999 is not a legal number
The average of 0 numbers is Undefined
注意:
- 一定要注意输出 numbers 和 number,细节问题!!!!!!
- 首先判断字符串长度,符合要求的字符串最多有8位,负号+4位数字+小数点+两位数字,超过8位直接pass
- 字符串有’-‘,’.’,’0-9’之外的符号,直接pass
- 负号只能出现在字符串首位,小数点只能有一个,小数点后面最多有两位数字,不符合要求的pass
- 我自己写了一个字符串转数字的方法,AC了
- 当然也可以用sscanf和sprintf函数,具体用法请点击,别人使用sscanf和sprintf函数AC的代码,请点击查看
代码:
#include <iostream>
#include <cstdio>
using namespace std;
double atof(string s);
int main()
{
int N;
cin >> N;
int countt = 0;
double sum = 0;
for(int i=0; i<N; i++){
string s;
cin >> s;
bool flag = true;//判断输入是否合法
bool isPoint = false;//判断前面是否已经有小数点
int point = 0;//计算小数点个数
int point_ = 0;//计算小数点后的位数
int F = 0;//计算负号的个数
if(s.size() > 8){//符合条件数字最多有8个字符
cout << "ERROR: "<< s<< " is not a legal number" << endl;
continue;
}
for(int j=0; j<s.size(); j++){
if(s[j]=='-' || s[j]=='.' || (s[j]-'0'>=0&&s[j]-'0'<=9)){//只能存在小数点,负号和数字
if(isPoint)//前面已经有小数点了
point_++;
if(s[0] == '-')//负号只能在第一位
F++;
if(s[j] == '.'){
point++;
isPoint = true;
}
if(point_>=3 || point>1 || (s[j]=='-'&&j!=0)){
flag = false;
break;
}
}else{
flag = false;
break;
}
}
if(!flag){//输入不合法
cout << "ERROR: "<< s << " is not a legal number" << endl;
}else{
double temp = atof(s);//将字符串转化为数字
if(temp<=1000 && temp>=-1000){
sum += temp;
countt++;
}else{
cout << "ERROR: "<< s << " is not a legal number" << endl;
}
}
}
if(countt == 1){
printf("The average of 1 number is %.2f", sum);//注意是number 不是numbers
}else if(countt > 1){
printf("The average of %d numbers is %.2f", countt, sum/countt);//精确到小数点后两位
}else{
printf("The average of 0 numbers is Undefined");
}
return 0;
}
double atof(string s){
double res = 0;
double res1 = 0;
bool flag = false;//判断是否是负数
bool isPoint = false;
double point_ = 1;//计算小数点后的位数
for(int i=0; i<s.size(); i++){
if(s[i] == '-'){
flag = true;
continue;
}
if(s[i] == '.'){
isPoint = true;
continue;
}
if(!isPoint){//整数部分
res = (s[i]-'0') + res*10;
}else{//小数部分
point_ *= 10;
res1 = (s[i]-'0') + res1*10;
}
}
if(point_ != 0)
res = res + res1/point_;
if(flag)//负数
return -res;
return res;
}