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 <cstdio>
#include <set>
#include <stack>
#include <iostream>
#include <vector>
#include <fstream>
#include <assert.h>
#include <map>
#include <set>
#include <algorithm>
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<n;t++)
    {
        cin>>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;
}
    

erow
46 声望5 粉丝

引用和评论

0 条评论