Для l oop для перебора всех значений и повторения процесса ввода, если переменная не найдена - C ++ - PullRequest
0 голосов
/ 05 мая 2020

Я все еще новичок в программировании и немного не понимаю, как заставить это работать. Я хочу l oop через все годы в массиве, и если он не найден, я хочу распечатать сообщение об ошибке и предложить пользователю повторить попытку. Я пробовал сделать оператор else, но он продолжает повторять сообщение об ошибке, пока не будет найден год. Есть предложения?

void option2(Vector<WindLogType> &windlog)
{

    int month = 0;
    int year;
    const int SIZE = windlog.size();
    float *averagetemp = new float[SIZE];
    float *sd = new float[SIZE];
    float *sum = new float[SIZE];
    float *sigma = new float[SIZE];
    float *nrofel = new float[SIZE];
    int *check = new int[SIZE];
    int counter = 0;
    int yearCheck = 0;

        while(yearCheck==0){
            cout << "Please enter a year: " << endl;
            cin >> year;

            for(int i = 0; i < SIZE; i++)
            {

                if(windlog[i].d.GetYear() == year)
                {

                    month = windlog[i].d.GetMonth();
                    counter = month;
                    nrofel[counter] = nrofel[counter] + 1;
                    sum[counter] += windlog[i].temp.GetTemperature();
                    averagetemp[counter] = (sum[counter]/nrofel[counter]);
                    sigma[counter] += (windlog[i].temp.GetTemperature() - averagetemp[counter])*(windlog[i].temp.GetTemperature() - averagetemp[counter]);
                    sd[counter] = sqrt((sigma[counter])/(nrofel[counter] - 1));
                    check[counter] = 1;

                }

            }
            for(int start = 1; start < 13; start++)
            {

            if(check[start] == 1)
            {
                cout << checkMonth(start) << ": " << averagetemp[start] << " degrees C, stdev: " << sd[start] << '\n';
            }
            else
            {
                cout << checkMonth(start) << ": No Data" << '\n';
            }


            }

            yearCheck = 1;

        }

        delete[] averagetemp;
        delete[] sum;
        delete[] sigma;
        delete[] sd;

}

Ответы [ 2 ]

0 голосов
/ 05 мая 2020

Вы даете массивы averagetemp, check et c. длина равна windlog.size(), однако позже вы будете использовать их, как если бы они содержали один элемент в месяц. Было бы лучше просто дать им длину 12.

Вы используете массивы, как если бы они начинались с нулевого значения в каждом элементе, но вы никогда не задаете им это значение. Вы можете поставить {} после объявления массива, чтобы начать его с нулевых значений.

void option2(Vector<WindLogType> &windlog)
{
    int year;
    static constexpr int monthsInYear = 12;
    const int SIZE = windlog.size();
    float averagetemp[monthsInYear];
    float sd[monthsInYear];

    while(true) {
        float sum[monthsInYear]{};
        float sigma[monthsInYear]{};
        float nrofel[monthsInYear]{};

        cout << "Please enter a year: " << endl;
        cin >> year;

        for(int i = 0; i < SIZE; i++)
        {
            if(windlog[i].d.GetYear() == year)
            {
                month = windlog[i].d.GetMonth();
                counter = month - 1;
                nrofel[counter] += 1;
                const float temperature = windlog[i].temp.GetTemperature()
                sum[counter] += temperature;
                averagetemp[counter] = (sum[counter]/nrofel[counter]);
                //This won't give an accurate value for sigma as it uses the current estimate of the mean, instead of the mean of all the samples
                //there are lots of ways of fixing this but which one is the most accurate will depend on sample size.
                sigma[counter] += (temperature - averagetemp[counter])*(temperature - averagetemp[counter]);
            }
        }
        bool yearsDataIsValid = true;
        for(int start = 0; start < 12; start++)
        {
            if(nrofel[start] == 0)
            {
                //making `checkMonth` zero based instead of adding 1 might be a good idea
                cout << checkMonth(start + 1) << ": No Data" << '\n';
                yearsDataIsValid = false;
                break;
            }
            if((nrofel[counter] - 1) == 0)
            {
                //I don't know what the standard deviation of one value is
                //but division by zero is an error
                sd[start] = 0;
            }
            else
            {
                sd[start] = sqrt((sigma[start]) / (nrofel[start] - 1))
            }
            cout << checkMonth(start + 1) << ": " << averagetemp[start] << " degrees C, stdev: " << sd[start] << '\n';
        }
        if(yearsDataIsValid)
        {
            break;
        }
    }
0 голосов
/ 05 мая 2020

используйте флаг yearCheck и добавьте оператор продолжения

void option2(Vector<WindLogType> &windlog)
{

    int month = 0;
    int year;
    const int SIZE = windlog.size();
    float *averagetemp = new float[SIZE];
    float *sd = new float[SIZE];
    float *sum = new float[SIZE];
    float *sigma = new float[SIZE];
    float *nrofel = new float[SIZE];
    int *check = new int[SIZE];
    int counter = 0;
    int yearCheck = 0;

        while(yearCheck==0){
            cout << "Please enter a year: " << endl;
            cin >> year;

            for(int i = 0; i < SIZE; i++)
            {

                if(windlog[i].d.GetYear() == year)
                {

                    month = windlog[i].d.GetMonth();
                    counter = month;
                    nrofel[counter] = nrofel[counter] + 1;
                    sum[counter] += windlog[i].temp.GetTemperature();
                    averagetemp[counter] = (sum[counter]/nrofel[counter]);
                    sigma[counter] += (windlog[i].temp.GetTemperature() - averagetemp[counter])*(windlog[i].temp.GetTemperature() - averagetemp[counter]);
                    sd[counter] = sqrt((sigma[counter])/(nrofel[counter] - 1));
                    check[counter] = 1;

///////////// CHANGE #1 /////////////////
yearCheck = 1;

                }

            }

///////////// CHANGE #2 /////////////////
if(!yearCheck )
continue;

            for(int start = 1; start < 13; start++)
            {

            if(check[start] == 1)
            {
                cout << checkMonth(start) << ": " << averagetemp[start] << " degrees C, stdev: " << sd[start] << '\n';
            }
            else
            {
                cout << checkMonth(start) << ": No Data" << '\n';
            }


            }

            yearCheck = 1;

        }

        delete[] averagetemp;
        delete[] sum;
        delete[] sigma;
        delete[] sd;

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...