-1
嗨,大家好我是新來的C++,但有一些與java的良好體驗。簡單的平均計算器c + +不能正常工作
我想做一個簡單的程序,需要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;
}
什麼是「隱藏的男生錯誤」?什麼是投入,預期產出和實際產出? – user463035818
解決此類問題的正確工具是您的調試器。在*堆棧溢出問題之前,您應該逐行執行您的代碼。如需更多幫助,請閱讀[如何調試小程序(由Eric Lippert撰寫)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)。至少,您應該\編輯您的問題,以包含一個[最小,完整和可驗證](http://stackoverflow.com/help/mcve)示例,該示例再現了您的問題,以及您在調試器。 –