リンクをクリックして、完全なソリューションの概要PAT B -AC
タイトル:
この問題の基本的な要件は非常に簡単です:N実数与えられ、その平均を算出します。しかし、合併症は、入力データの一部が違法であってもよいことです。区間[-1000,1000]入力での実数である「合法的な」、と、小数点以下1桁に最も正確で。あなたは平均値を計算すると、これらの不正なデータはカウントされませ。
入力フォーマット:
最初の行の入力は、正の整数N(≤100)が与えられます。次いで、ラインNの実数を与えられた数の間のスペースで区切られました。
出力フォーマット:
各不正入力に対する出力ラインにおいてERROR: X is not a legal number
、X
入力されます。最終的な出力とライン:法的入力の数であるが、平均値その二進場所です。平均値で、計算できない場合は、交換。もし1、出力。The average of K numbers is Y
K
Y
Undefined
Y
K
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
私のコード:
#include<iostream>
#include<cstdio>
#include<vector>
#include<string>
#include<set>
#include<map>
#include<algorithm>
#include<cmath>
#include<ctime>
#include<cstring>
#include<sstream>
using namespace std;
//有的时候题目是一起做的,所以会有不需要的头文件
int main()
{
int N;
cin>>N;
int K=0;
double sum=0;
for(int i=0;i<N;i++)
{
string str_input;
cin>>str_input;
string str(str_input);
double num=0;
bool flag_isnum=true;
bool flag_minus=false;
bool flag_first=true;
int flag_point=0;
while(str.length()>0)
{
if((str[0]>='0'&&str[0]<='9')||str[0]=='.'||str[0]=='-'||flag_isnum)
{
if(flag_point>0)flag_point++;//记录小数点的位置
if(str[0]=='.')
{
if(flag_point!=0)flag_isnum=false;
else flag_point++;
}
else if(str[0]=='-')
{
if(flag_first)flag_minus=true;
else flag_isnum=false;
}
else
{
num=num*10+str[0]-'0';
}
}
else
flag_isnum=false;
str.erase(0,1);
flag_first=false;
}
if(flag_point)flag_point--;
num=num*pow(0.1,flag_point);
if(flag_isnum&&flag_point<=2&&num>=-1000&&num<=1000)
{
if(flag_minus)sum-=num;
else sum+=num;
K++;
}
else
cout<<"ERROR: "<<str_input<<" is not a legal number"<<endl;
}
cout<<"The average of "<<K;
if(K==1)cout<<" number is ";
else cout<<" numbers is ";
if(K==0)cout<<"Undefined"<<endl;
else printf("%.2f",sum/K);
return 0;
}
いくつかの特殊なケースに注意してください。
- 唯一の最初の場所に表示される場合があります
0-5
0から0.5
- -0.5
最初に私は-00.5と-100.05 -0.05と最も困難な、と後での区別は私はあまり考えていることを見つけたと思います