Проблема заключается в том, что вы ищете самое большое количество осадков, прежде чем вы получили данные о количестве осадков от пользователя.
Переместить эту строку:
int maxMonthPosition = searchHighestMonth(inchesOfRain, months);
После ввода для цикла.
Я пошел дальше и снова протестировал весь ваш код, перенаправив stdin (cin) из строки ввода, что я считаю очень полезным для тестирования, поэтому мне не нужно продолжать вводить. вот мой код:
#include <iostream>
#include <sstream>
#include <iomanip>
using namespace std;
double yearlyRainAverage(double[], const int);
double smallestRainfall(double [], const int);
double largestRainfall(double [], const int);
int searchHighestMonth(double inchesofrain[], int value) {
int max = 0;
for (int i = 1; i < value; ++i) {
if (inchesofrain[max] < inchesofrain[i]) {
max = i;
}
}
return max;
}
int main() {
//#define testing // comment this line out to use std::cin for input
#ifdef testing
// code to get stdin input from a local buffer
std::string input_string{"4 5 6 7 8 9 10 3 2 3 4 5"};
std::streambuf *orig = std::cin.rdbuf();
std::istringstream input(input_string);
std::cin.rdbuf(input.rdbuf());
#endif
const int months = 12;
double inchesOfRain[months];
double sumOfAllMonths = 0;
for (int count = 0; count < months; count++) {
cout << "Enter the rainfall (in inches) for month #" << count + 1 << ": " << std::endl;
cin >> inchesOfRain[count];
sumOfAllMonths += inchesOfRain[count];
while (inchesOfRain[count] < 0) {
cout << "Rainfall must be 0 or more.\n";
cout << "please re-enter: " << endl;
cout << "Enter the rainfall (in inches) for month #" << count + 1 << ": " << std::endl;
cin >> inchesOfRain[count];
}
}
int maxMonthPosition = searchHighestMonth(inchesOfRain, months);
cout << fixed << showpoint << setprecision(2) << endl;
cout << "the total rainfall for the year is " << sumOfAllMonths << " inches" << endl;
cout << "the average is " << yearlyRainAverage(inchesOfRain, months) << " inches" << endl;
// cout<<"The smallest amount of rainfall was: "<<smallestRainfall(inchesOfRain, 12)<<" inches ";
// cout<<"in month "<<(monthPosition+1)<<endl;
cout << "The largest amount of rainfall was: " << largestRainfall(inchesOfRain, 12) << " inches ";
cout << "in month " << maxMonthPosition + 1 << endl;
#ifdef testing
std::cin.rdbuf(orig);
#endif
return 0;
}
double yearlyRainAverage(double inchesofrain[], const int months) {
double sum = 0;
for (int i = 0; i < months; i++) {
sum += inchesofrain[i];
}
return sum / months;
}
double smallestRainfall(double inchesofrain[], const int months) {
double smallest;
int i;
smallest = inchesofrain[0];
for (i = 0; i < months; i++) {
if (inchesofrain[i] < smallest) {
smallest = inchesofrain[i];
}
}
return smallest;
}
double largestRainfall(double inchesofrain[], const int months) {
double largest;
int i;
largest = inchesofrain[0];
for (i = 0; i < months; i++) {
if (inchesofrain[i] > largest) {
largest = inchesofrain[i];
}
}
return largest;
}
Если Вашей программой является Приложение Windows, а не Консольное приложение, интерпретатор команд не ожидает ее для завершения (прежде чем Вы будете нажимать OK, будете смотреть на командное окно, и Вы будете видеть, что это готово к следующей команде).
Если это верно, создавая Ваше приложение, поскольку Консольное приложение подсистемы решило бы проблему. Если необходимо работать как Приложение Windows, Вы могли бы попытаться ожидать команды, чтобы завершиться и видеть, работает ли это (я не попробовал это, но она походит на хороший подход):
start /wait a.exe
echo %ERRORLEVEL%
Для %ERRORLEVEL%
для работы у Вас должны быть включенные расширения команды (который я думаю, значение по умолчанию, так как Бог знает когда).
Попытка, делающая:
echo %CMDEXTVERSION%
Видеть, включены ли расширения. Я добираюсь'2
'вывод, когда они идут и"%CMDEXTVERSION%
"когда они выключены.
Можно также протестировать errorlevel использование старого стиля:
if errorlevel 1 echo errorlevel is 1 or more...
Это должно работать независимо от расширений или если кто-то установил переменную среды с именем"ERRORLEVEL
"