当前位置:编程学习 > C/C++ >>

UVA 10137 - The Trip(旅行)

/*
* 10137 - The Trip
* 作者 仪冰
* 语言 C++
* QQ 974817955
*
* 精度处理一小弄。n个学生,每个学生有一个花费,
* 求出平均值,求小于平均值的总和(less),
* 求出大于平均值的总和(greatly),最后再进行less和grealy比较,输出最大的。
*/

#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;

const int SIZE = 1000;

const double EXP = 1e-8;

int main()
{
    int nStudents = 0;             //学生总数
    double everyStudentCost[SIZE]; //存储每个学生的花费
    double totalCost = 0.0;        //花费总数
    double average = 0.0;          //平均值
    double less = 0.0;             //少于平均值
    double greatly = 0.0;          //多于平均值

    while (cin >> nStudents)
    {
        if (nStudents == 0)
        {
            break;
        }

        //初始化
        totalCost = 0.0;
        average = 0.0;
        less = 0.0;
        greatly = 0.0;

        //输入
        for (int i=0; i<nStudents; i++)
        {
            cin >> everyStudentCost[i];
        }

        //求总花费
        for (int i=0; i<nStudents; i++)
        {
            totalCost += everyStudentCost[i];
        }

        //求平均值
        average = totalCost / nStudents;

        //求less和greatly的值
        for (int i=0; i<nStudents; i++)
        {
            if (everyStudentCost[i] < average)
            {
                //精度处理,保留两位小数。先乘以100取其整数部分,然后再除以100.00
                less += ((int)(100*(average - everyStudentCost[i])) / 100.00);
            }
            else
            {
                greatly += ((int)(100*(everyStudentCost[i] - average)) / 100.00);
            }
        }

        //求出less和greatly中的最小值
        if (less > greatly)
        {
            cout.precision(2);
            cout.setf(ios::fixed | ios::showpoint);
            cout << "$" << less << endl;
        }
        else
        {
            cout.precision(2);
            cout.setf(ios::fixed | ios::showpoint);
            cout << "$" << greatly << endl;
        }
    }

    return 0;
}

 

补充:软件开发 , C++ ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,