1054

2017-09-04  本文已影响0人  峡迩
// PATn.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<iostream>
#include<iomanip>
#include<string>


using namespace std;

bool check_number(string &s)
{
    const string s_f = "0123456789-.";

    for (auto r : s)//判断是否含有除数字、负号、点号外的字符!
    {
        if (s_f.find(r) == string::npos)
            return false;
    }

    if (s.find_first_of('.') != s.find_last_of('.'))//判断是否含有多个字符‘.’
        return false;

    if (s.find('.')!=string::npos)
    {
        if ((s.size() - s.find('.')) > 3)//判断小数点的位数是否大于2!
            return false;
    }

    double tmp = stod(s);

    if (tmp < -1000 || tmp>1000)//判断是否越界!
        return false;

    return true;            //通过所有判断后则满足条件!
}

int main()
{
    
    unsigned n;
    cin >> n;

    string tmp;
    double sum=0;
    unsigned count = 0;
    for (unsigned i = 0; i < n; ++i)
    {
        cin >> tmp;
        if (check_number(tmp))
        {
            sum = sum + stod(tmp);
            count = count + 1;
        }
        else
        {
            cout << "ERROR: " << tmp << " is not a legal number" << endl;
        }
    }

    cout.setf(ios::fixed);
    if(count == 0)
        cout <<"The average of 0 numbers is Undefined";
    else
    {
        auto out = sum / (count*1.0);
        if (count == 1)
            cout << "The average of " << count << " number is " << setprecision(2) << out;
        else
            cout  << "The average of " << count << " numbers is " << setprecision(2)<<out;
    }
        
    system("pause");
    return 0;
}

上一篇 下一篇

猜你喜欢

热点阅读