测试点 2:k==1 number没有s
测试点 3:12. 这种是合法的
#include<cstdio>
#include<iostream>
#include<string>
using namespace std;
int n;
string s;
bool check(string s)
{
if( (s[0]=='+'||s[0]=='-') && s.size()==1) return false;
if(s[0]=='+'||s[0]=='-') s=s.substr(1);
int k=0,index=0;
for(int i=0;i<s.size();i++)
{
if(s[i]=='.') k++,index=i+1;
else if(s[i]<'0'||s[i]>'9') return false;
}
if(k>=2) return false;
if(k==0) return true;
if( (s.size()-index)>2 ) return false;
return true;
}
int main(void)
{
cin>>n;
double sum=0;
int cnt=0;
bool flag=false;
for(int i=0;i<n;i++)
{
cin>>s;
if(check(s))
{
double temp=stod(s);
if(temp>=-1000.0&&temp<=1000.0) sum+=temp,cnt++,flag=true;
else printf("ERROR: %s is not a legal number\n",s.c_str());
}
else printf("ERROR: %s is not a legal number\n",s.c_str());
}
if(flag&&cnt!=1) printf("The average of %d numbers is %.2lf\n",cnt,sum/cnt);
else if(flag) printf("The average of %d number is %.2lf\n",1,sum);
else printf("The average of 0 numbers is Undefined");
return 0;
}
#include<bits/stdc++.h>
using namespace std;
int cnt,t;
double sum;
bool check(string s)
{
string temp=s;
int k=0;
if(temp[0]=='-'||temp[0]=='+') temp=temp.substr(1);
for(int i=0;i<temp.size();i++)
{
if(temp[i]=='.') k++;
else if(temp[i]<'0'||temp[i]>'9') return false;
}
if(k>1) return false;
if(k)
{
int l=temp.find('.');
int len=temp.size()-l-1;
if(len>2) return false;
}
double a=stod(s);
if(a>=-1000.0&&a<=1000.0) return true;
else return false;
}
int main(void)
{
cin>>t;
while(t--)
{
string s; cin>>s;
if(check(s)) cnt++,sum+=stod(s);
else printf("ERROR: %s is not a legal number\n",s.c_str());
}
if(cnt>1) printf("The average of %d numbers is %.2lf",cnt,sum/cnt);
else if(cnt==1) printf("The average of %d number is %.2lf",cnt,sum/cnt);
else printf("The average of 0 numbers is Undefined");
return 0;
}