当前位置:网站首页>Pat b1054 average (20 points)
Pat b1054 average (20 points)
2022-06-25 19:55:00 【Madness makes freedom】
1054 averaging (20 branch )
The basic requirements of this question are very simple : Given N A real number , Calculate their average . But the complexity is that some of the input data may be illegal . One “ legal ” The input is [−1000,1000] The real number in the interval , And at most accurate to the decimal point 2 position . When you calculate the average , You can't count those illegal data .
Input format :
Enter the first line to give a positive integer N(≤100). The next line shows N A real number , Numbers are separated by a space .
Output format :
For every illegal input , Output in one line ERROR: X is not a legal number, among X It's input . Finally, output the result in one line :The average of K numbers is Y, among K Is the number of legal inputs ,Y It's their average , Accurate to the decimal point 2 position . If the average cannot be calculated , Then use Undefined Replace Y. If K by 1, The output The average of 1 number is Y.
sample input 1:
7
5 -3.2 aaa 9999 2.3.4 7.123 2.35
sample output 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
sample input 2:
2
aaa -9999
sample output 2:
ERROR: aaa is not a legal number
ERROR: -9999 is not a legal number
The average of 0 numbers is UndefinedFor this question , It's the longest question I've spent so far , Now recall , It's really a bit annoying . For output , A number is singular when it is legal number, In other cases numbers, At first, I didn't read the questions carefully , All output numbers, Another half day , But in the end, the code I wrote passed only three test data , There's another one that doesn't work .
Finally, I read other people's blogs , He sent Liu Shen's code , Have to say sscanf and sprintf Function when processing some strings , It really works .
I finally read other people's blogs , I wrote three codes , Summed up a few points :
- For a relatively complex situation , It is better to write a function , Many of the same situations can be merged , Such as , This question , Return the data that does not conform to the meaning of the question false, Others will return true. All of them are written in the main function , It is possible to omit , From the beginning of the first code, I missed the innermost if sentence , No consideration is given to greater than 1000 Or less than -1000 The situation of .
- else if(flag==1)
{
double dou=str_dou(str);
if(i-j<=3)
{
if(dou>=-1000&&dou<=1000)
{
++count;
average+=dou;
}
else
ans.push_back(str);
} - It works string Just use string, Don't use tradition c character string , Because sometimes we don't know how big a string to use , Take this question for example . At the beginning of this question, I used the size of 20 Character number of , Thinking about 20 It must be able to hold every data , As a result, a set of data can not pass , puzzled , Finally, the size of the array is changed to 50 Just passed . Be careful. I can't stand it .
- Although only this question took me a lot of time , But it's worth it , After all, I have gained something . Before I finally changed the code , Submit when you see everything right , A feeling of joy welled up in my heart .
Don't talk much , Put it in code. !!!
This is what I wrote first , Not right at first , The following changes are correct . Now look at it. , It's really complicated .
#include <iostream>
#include <vector>
#include <string>
#include <cstdio>
using namespace std;
double str_dou(string s);
int main()
{
int n;
cin >> n;
string str;
double average=0;
int count=0; //count Statistics of legal data
vector<string> ans; //ans Storing illegal data
while(n--)
{
cin >> str;
int i,j=0, flag=0; //j and flag Record the position and number of decimal points respectively
for(i=0;i<str.size();i++)
{
if(str[i]=='-')
{
if(i!=0)
{
ans.push_back(str);
break;
}
}
if(str[i]=='.')
{
j=i;
flag++;
}
if(!isdigit(str[i])&&str[i]!='.'&&str[i]!='-')
{ // If it is a non numeric symbol other than the decimal point or minus sign
ans.push_back(str);
break;
}
}
if(i==str.size())
{
if(flag==0)
{
double dou=str_dou(str);
if(dou>=-1000&&dou<=1000)
{
++count;
average+=dou;
}
else
ans.push_back(str);
}
else if(flag==1)
{
double dou=str_dou(str);
if(i-j<=3)
{
if(dou>=-1000&&dou<=1000)
{
++count;
average+=dou;
}
else
ans.push_back(str);
}
else
{
ans.push_back(str);
}
}
else
{
ans.push_back(str);
}
}
}
for(int i=0;i<ans.size();++i)
{
printf("ERROR: %s is not a legal number\n",ans[i].c_str());
}
if(count==1)
printf("The average of %d number is %.2f\n",count,average);
else if(count>1)
printf("The average of %d numbers is %.2f\n",count,average/count);
else
printf("The average of %d numbers is Undefined\n",count);
return 0;
}
double str_dou(string s)
{
double dou=0,pos=0.1;
int flag=1,judge=1;
for(auto a:s)
{
if(a=='-')
{
judge=-1;
continue;
}
if(a=='.')
{
flag=0;
continue;
}
if(flag)
dou=dou*10+a-'0';
else
{
dou+=(a-'0')*pos;
pos*=0.1;
}
}
dou*=judge;
return dou;
}
This is a function that writes all the cases separately , How do you say , It feels better than the previous one .
#include <iostream>
#include <vector>
#include <string>
#include <cstdio>
using namespace std;
double str_dou(string s);
bool judge(string str);
int main()
{
int n;
cin >> n;
string str;
double average=0;
int count=0;
while(n--)
{
cin >> str;
if(!judge(str))
printf("ERROR: %s is not a legal number\n",str.c_str());
else
{
average+=str_dou(str);
++count;
}
}
if(count==1)
printf("The average of %d number is %.2f\n",count,average);
else if(count>1)
printf("The average of %d numbers is %.2f\n",count,average/count);
else
printf("The average of %d numbers is Undefined\n",count);
return 0;
}
double str_dou(string s)
{
double dou=0,pos=0.1;
int flag=1,judge=1;
for(auto a:s)
{
if(a=='-')
{
judge=-1;
continue;
}
if(a=='.')
{
flag=0;
continue;
}
if(flag)
dou=dou*10+a-'0';
else
{
dou+=(a-'0')*pos;
pos*=0.1;
}
}
dou*=judge;
return dou;
}
bool judge(string str)
{
int i,j=0, flag=0;
for(i=0;i<str.size();i++)
{
if(str[i]=='-')
{
if(i!=0)
return false;
}
if(str[i]=='.')
{
j=i;
flag++;
}
if(!isdigit(str[i])&&str[i]!='.'&&str[i]!='-')
return false;
}
if(flag>1)
return false;
else if(flag==1)
{
if(i-j>3)
return false;
double dou=str_dou(str);
if(dou<-1000||dou>1000)
return false;
}
else
{
double dou=str_dou(str);
if(dou<-1000||dou>1000)
return false;
}
return true;
}
Finally, I read the code of Liu Shen , Write out the .
#include <cstdio>
#include <cctype>
#include <cstring>
#include <cmath>
using namespace std;
int main()
{
int n;
scanf("%d",&n);
char s[50],ans[50];
double db;
int count=0;
double average=0;
while(n--)
{
cin >> s;
sscanf(s,"%lf",&db);
sprintf(ans,"%.2f",db);
int len=strlen(s);
int flag=0;
for(int i=0;i<len;++i)
{
if(s[i]!=ans[i])
{
flag=1;
break;
}
}
if(flag==1||db>1000||db<-1000)
{
printf("ERROR: %s is not a legal number\n",s);
}
else
{
average+=db;
++count;
}
}
if(count==1)
printf("The average of %d number is %.2f\n",count,average);
else if(count>1)
printf("The average of %d numbers is %.2f\n",count,average/count);
else
printf("The average of %d numbers is Undefined\n",count);
return 0;
}边栏推荐
- The functions in the applet page are better than those in app JS first execution solution
- Trend ea- fixed stop loss and profit per order
- JS asynchronism (III. usage of generator and async/await)
- Wechat applet swiper simple local picture display appears large blank
- 3、 Hikaricp source code analysis of connection acquisition process III
- How to understand var = a = b = C = 9? How to pre parse?
- 一、HikariCP获取连接流程源码分析一
- Applet password input box
- Use of serialize() and serializearray() methods for form data serialization
- 2、 Hikaricp source code analysis of connection acquisition process II
猜你喜欢

Why are life science enterprises on the cloud in succession?

New features of php7

Yaml configuration

Two types of attribute injection methods

Mqtt+ardunio+esp8266 development (excluding mqtt server deployment)

Process of vacuum and vacuum full

DARKHOLE 2

Profile path and name

Use of serialize() and serializearray() methods for form data serialization

Miner's Diary: why should I go mining on April 5, 2021
随机推荐
Suddenly found that the screen adjustment button can not be used and the brightness can not be adjusted
The meanings of /32, /48, /64 in IPv6 addresses
Randomly generate 100 non repeating numbers between 1 and 150 and put them in the array
五、HikariCP源码分析之初始化分析二
Electronic package to generate EXE file
DataX script task development record
JQ implements tab switching
1、 Hikaricp source code analysis of connection acquisition process I
Uni app through uni Navigateto failed to pass parameter (pass object)
请问同花顺开户安全吗?
Why are life science enterprises on the cloud in succession?
2020-12-09 laravel . Env file loading mechanism process
Validation of TTF font by validator of laravel
Error record: preg_ match(): Compilation failed: range out of order in character class at offset 13
Web components - Basics
2、 Hikaricp source code analysis of connection acquisition process II
Alicloud centos8.0 installing mysql8
Principles of MySQL clustered index and non clustered index
PHP little knowledge record
Applet wx Request encapsulation