简单平均计算器c++不能正常工作

Simple average calculator c++ not working correctly

本文关键字:常工作 工作 不能 计算器 c++ 简单      更新时间:2023-10-16

大家好,我是c++新手,但对java有一些很好的经验。

我想做一个简单的程序,需要5个整数(作为裁判分数)。最大和最小的分数被丢弃,必须从剩下的中间3个分数中计算平均值。

我认为这将是相当简单的,但由于某些原因,我的程序总是给我一个比它应该的稍微大一点的答案。

我还应该说明,答案可以是实数,而输入必须是整数。

下面是我到目前为止得到的,它几乎完成了,但有一些隐藏的学生错误,我没有发现几个小时。

我知道可能有其他更有效的方法,但这是我能想到的最好的方法,因为我才刚刚开始使用c++。

任何帮助将非常感激!!

#include <iostream>
using namespace std;
int getSmallest(int first, int second, int third, int fourth, int fifth);
int getLargest(int first, int second, int third, int fourth, int fifth);
double calculateAverage(int largest, int smallest, int sum);
int main()
{
    int first, second, third, fourth, fifth;
    int smallest, largest, sum;
    //double ave;
    //read input of 5 scores from judges
    cin >> first;
    cin >> second;
    cin >> third;
    cin >> fourth;
    cin >> fifth;
    smallest = getSmallest ( first, second, third, fourth, fifth );
    largest = getLargest ( first, second, third, fourth, fifth );
    sum = (first + second + third + fourth + fifth);
    //ave = calculateAverage(largest, smallest, sum);
    //cout << ave << endl;
    cout << "The average is " << (double)calculateAverage(largest, smallest, sum) << endl;
    return 0;
}
int getSmallest(int first, int second, int third, int fourth, int fifth)
{
    int smallest = 0;
    if ( first <= smallest )
    {
        smallest = first;
    }
    if ( second <= smallest )
    {
        smallest = second;
    }
    if ( third <= smallest )
    {
        smallest = third;
    }
    if ( fourth <= smallest )
    {
        smallest = fourth;
    }
    if ( fifth <= smallest )
    {
        smallest = fifth;
    }
    return smallest;
}
int getLargest(int first, int second, int third, int fourth, int fifth)
{
    int largest = 0;
    if ( first >= largest )
    {
        largest = first;
    }
    if ( second >= largest )
    {
        largest = second;
    }
    if ( third >= largest )
    {
        largest = third;
    }
    if ( fourth >= largest )
    {
        largest = fourth;
    }
    if ( fifth >= largest )
    {
        largest = fifth;
    }
    return largest;
}
double calculateAverage(int largest, int smallest, int sum)
{
    return (((double)sum) - ((double)largest + (double)smallest)) / 3.0;
}

getSmallest例程中,您必须设置

int smallest = INT_MAX;

smallest无论您输入什么都将为0。

(包括<climits>, INT_MAX可用)

编辑:它工作,但不是有效的。您可以保存一个测试(在这种情况下不需要INT_MAX),因为第一个条件将始终为真:

int getSmallest(int first, int second, int third, int fourth, int fifth)
{
    int smallest = first;
    if ( second <= smallest )
    {
        smallest = second;
    }

同样的优化也适用于getLargest

int getLargest(int first, int second, int third, int fourth, int fifth)
{
    int largest = first;
    if ( second >= largest )
    {
        largest = second;
    }