Нахождение индекса массива в функции в C ++ - PullRequest
0 голосов
/ 31 марта 2019

У меня есть домашнее задание, и я его уже выполнил.где я застрял ... В основном мне нужно получить наибольшее количество осадков и показать его (что я уже сделал это), а также номер месяца.

Здесь у меня сильная головная боль ... не могли бы вы, ребята, помочь мне с каким-нибудь кодом?

#include <iostream>
#include <iomanip>
using namespace std;

double yearlyRainAverage(double[], const int);
double smallestRainfall(double [], const int);
double largestRainfall(double [], const int);
int searchHighestMonth(double[], int);

int main() {

    const int months = 12;
    double inchesOfRain[months];
    double sumOfAllMonths=0;


    int maxMonthPosition = searchHighestMonth(inchesOfRain, months);

    for (int count = 0; count < months; count++)
    {
        cout<<"Enter the rainfall (in inches) for month #"<< count + 1<<":  ";
        cin>>inchesOfRain[count];

        sumOfAllMonths += inchesOfRain[count];


        if(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<<":  ";
            cin>>inchesOfRain[count];

        }

    }
    cout << fixed << showpoint << setprecision(2) << endl;

    cout<<"the total rainfall for the year is "<<sumOfAllMonths<<" inches"<<endl;
    cout<<"the average is "<<yearlyRainAverage(inchesOfRain, 12)<<" 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;

    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;
}

Вот где, я думаю, проблема.Я думаю, что моя логика неверна.Но я не уверен.

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;
}

Ответы [ 2 ]

1 голос
/ 31 марта 2019

Проблема в том, что вы ищете самое большое количество осадков до того, как вы взяли данные о количестве осадков от пользователя.

Переместите эту строку:

    int maxMonthPosition = searchHighestMonth(inchesOfRain, months);

После ввода дляloop.

Я продолжил и снова протестировал весь ваш код, перенаправив 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;
}
0 голосов
/ 31 марта 2019

Ваша функция searchHighestMonth () почти хороша. Но его цикл должен начинаться с 0, а не с 1, как в остальной части вашего кода. Цикл составляет от 0 до 11, если это полный год с 12 месяцами. Кроме того, это будет более читабельным, если вы сохраните текущее максимальное значение дождя в некоторой переменной.

int searchHighestMonth(double inchesofrain[], int monthcount){

    double maxrain = -1.0;
    int max = -1;

    for ( int i=0; i < monthcount; ++i) {
        if ( maxrain < inchesofrain[i] ) {
            maxrain = inchesofrain[i];
            max = i;
        }
    }
    return max;
}

Дополнительное замечание : В реальном производственном коде вы, вероятно, захотите использовать объекты std :: vector, которые сохраняют свой собственный размер, а не простые старые массивы в стиле C.

Дополнительное замечание : если вы хотите дать своему пользователю второй шанс ввести правильное неотрицательное значение количества осадков, вы должны сделать это за до , включая это значение в сумму.

...