博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
PAT 题解
阅读量:6328 次
发布时间:2019-06-22

本文共 2094 字,大约阅读时间需要 6 分钟。

1108. Finding Average (20)

The basic task is simple: given N real numbers, you are supposed to

calculate their average. But what makes it complicated is that some of
the input numbers might not be legal. A "legal" input is a real number
in [-1000, 1000] and is accurate up to no more than 2 decimal places.
When you calculate the average, those illegal numbers must not be
counted in.

Input Specification:

Each input file contains one test case. For each case, the first line

gives a positive integer N (<=100). Then N numbers are given in the
next line, separated by one space.

Output Specification:

For each illegal input number, print in a line "ERROR: X is not a

legal number" where X is the input. Then finally print in a line the
result: "The average of K numbers is Y" where K is the number of legal
inputs and Y is their average, accurate to 2 decimal places. In case
the average cannot be calculated, output "Undefined" instead of Y. In
case K is only 1, output "The average of 1 number is Y" instead.

这道题本来挺简单的,但是要求检查输入格式。看了一下通过率还是挺惨的。

这种题第一个想到的是正则,然而不知道为什么使用正则会导致编译超时。?_ ??
既然这样那就手工构造DFA,效率高的可怕。
还有一个办法就是利用sprintf讲读入的浮点数再比较一下。sscanf(a, "%lf", &f);sprintf(b, "%.2lf",f);

#include 
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;bool match_int1(char *p){ if(*p=='-') p++; int a=0;I: if(*p>='0'&&*p<='9') {p++;goto I;} if(*p==0) return true; if(*p=='.') {p++;goto F;} return false;F: if(a<2&&*p>='0'&&*p<='9') {p++,a++;goto F;} if(*p==0) return true; return false;}int main() { int n; #ifdef _DEBUG ifstream cin("input.txt");#endif cin>>n; char a[50], b[50]; double sum=0;int num=0; for(int t=0;t
>a; double f; sscanf(a, "%lf", &f); if(!match_int1(a)||f<-1000||f>1000) printf("ERROR: %s is not a legal number\n",a); else { num++; sum+=f; } } if(num == 1) { printf("The average of 1 number is %.2lf", sum); } else if(num > 1) { printf("The average of %d numbers is %.2lf", num, sum / num); } else { printf("The average of 0 numbers is Undefined"); } return 0;}

转载地址:http://kiwoa.baihongyu.com/

你可能感兴趣的文章
cocos2d JS 自定义事件分发器(接收与传递数据) eventManager
查看>>
thinkPHP 模板的使用技巧(十三)
查看>>
简简单单搞掂恼人的Laravel 5安装
查看>>
.NET 即时通信,WebSocket服务端实例
查看>>
清除与清空节点
查看>>
BZOJ 1174: [Balkan2007]Toponyms
查看>>
linux下的C语言开发 GDB的例子
查看>>
图书馆接口设计
查看>>
linux中根目录下各个目录的作用
查看>>
io_service work 的作用
查看>>
儿童二类疫苗是否有必要接种
查看>>
1.spring boot要求最低jdk1.8,平安默认1.6问题,-》安装JDK1.8 2.maven 3.3.3要求最低jdk1.7->安装jdk 1.8...
查看>>
C++ 退出双层for循环,解决 break、return、continue无法实现问题
查看>>
Schema中elementFormDefault="qualified"所起的作用
查看>>
【JavaScript从入门到精通】第一课 初探JavaScript魅力-01
查看>>
web.xml配置错误页面,及输出错误信息
查看>>
浏览器份额查询
查看>>
项目管理原则搜集
查看>>
计算机加电后操作系统启动过程
查看>>
Java日志框架-Logback手册中文版以及官方配置文档教程
查看>>