本题的基本要求非常简单:给定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”。
idea:分层次走:
1.先判断字符串中时候只有数字、负号'-'及小数点'.'这三种字符
2.统计负号个数,小数点个数是否唯一
3.判断有一个负号,其是否在首位,小数点位置是否正确等,例如不合法情况 -.12 -.
4.没有负号,小数点位置是否正确等,如.123
注意:有一个测试点没有通过,实在还想不出有哪些情况,望大神指教
#include<iostream>
#include<cstring>
#include<ctype.h>
#include<cstdlib>
#include<iomanip>
using namespace std;
int main(){
int n;
cin>>n;
float sum=0;
int count=0;
for(int i=0;i<n;i++){
string a;
cin>>a;
int len=a.length(),coun1=0;
for(int j=0;j<len;j++){
if(isdigit(a[j])||a[j]=='.'||a[j]=='-'){
coun1++;//合法字符个数
}
}
if(coun1==len){
int coun2=0;
for(int j=0;j<len;j++){
if(a[j]=='.'){
coun2++;//小数点个数
}
}
int coun3=0;
for(int j=0;j<len;j++){
if(a[j]=='-'){
coun3++;//负号个数
}
}
if(coun3==1){//有一个负号
if(a[0]=='-'){
if(coun2==1){//有一个小数点
for(int j=0;j<len;j++){
if(a[j]=='.'){
if(j==1){
cout<<"ERROR: "<<a<<" is not a legal number"<<endl;
}else{
len=len-j;
if(len<=3&&len>=2&&(atof(a.c_str())>=-1000&&atof(a.c_str())<=1000)){//精确到1位或2位
count++;
sum+=atof(a.c_str());
}else{
cout<<"ERROR: "<<a<<" is not a legal number"<<endl;
}
}
}
}
}else if(coun2==0){//没有小数点
if(len>=2&&(atof(a.c_str())>=-1000&&atof(a.c_str())<=1000)){
count++;
sum+=atof(a.c_str());
}else{
cout<<"ERROR: "<<a<<" is not a legal number"<<endl;
}
}else{
cout<<"ERROR: "<<a<<" is not a legal number"<<endl;
}
}else{
cout<<"ERROR: "<<a<<" is not a legal number"<<endl;
}
}else if(coun3==0){//没有负号
if(coun2==1){//有一个小数点
for(int j=0;j<len;j++){
if(a[j]=='.'){
if(j==0){
cout<<"ERROR: "<<a<<" is not a legal number"<<endl;
}else{
len=len-j;
if(len<=3&&len>=2&&(atof(a.c_str())>=-1000&&atof(a.c_str())<=1000)){
count++;
sum+=atof(a.c_str());
}else{
cout<<"ERROR: "<<a<<" is not a legal number"<<endl;
}
}
}
}
}else if(coun2==0){//没有小数点
if(len>=1&&(atof(a.c_str())>=-1000&&atof(a.c_str())<=1000)){
count++;
sum+=atof(a.c_str());
}else{
cout<<"ERROR: "<<a<<" is not a legal number"<<endl;
}
}else{
cout<<"ERROR: "<<a<<" is not a legal number"<<endl;
}
}else{
cout<<"ERROR: "<<a<<" is not a legal number"<<endl;
}
}else{
cout<<"ERROR: "<<a<<" is not a legal number"<<endl;
}
}
if(count==0){
cout<<"The average of 0 numbers is Undefined";
}else if(count==1){
cout<<"The average of "<<count<<" number is "<<fixed<<setprecision(2)<<sum/count;
}else{
cout<<"The average of "<<count<<" numbers is "<<fixed<<setprecision(2)<<sum/count;
}
return 0;
}