Статистический калькулятор выводит бесконечный цикл

0

Моя программа предназначена для того, чтобы принимать от пользователя 3-30 значений и запускать через несколько функций для вычисления среднего, среднего и стандартного отклонения. Однако, как только я поставил набор значений тестового примера, мой результат приводит к беспорядочному беспорядку того, что я предполагаю, что это бесконечный цикл.

Я полностью потерял то, что именно я сделал неправильно. Я был бы очень признателен за любую помощь.

#include <iostream>
#include <iomanip> // for Setprecision
#include <cmath> // for pow and sqrt

using namespace std;

int main()
{
    // Declare Local Variables
    const int SIZE=30.0;
    double array[SIZE];
    int count = 0;
}
//Module: inputArrayValues
//Description: Ask the user to input values between 3 and 30 elements for the array to hold. Also validates that the user inputs a total of values between 3 and 30.
void inputArrayValues (double array[], int SIZE, int &count)
{
    double number = 0;
    const double SENTINEL = -1.0;
    // Basic information about what the user can input. Does not repeat.
    cout << "Please enter values one at a time." <<endl;
    cout << "Up to a maximum of 30 values and a minimum of 3 values." << endl;
    cout << "Only positive values are accepted or the program will not work." << endl;
    cout << "With the exception, please enter the value -1.0 to stop entering values." << endl;

    // While Loop
    // Variable count is counting how many values the user inputs for later calculation
    for (int i = 0; i < SIZE; i++)
    {
        while (number!= SENTINEL)
        {
            cout << "Please enter a value or enter -1.0 to stop entering values" << endl;
            cin >> number;
            array[i] = number;
            if (number != SENTINEL)
            {
                count++;
            }

        }
    }

    if (count < 3 || count > SIZE)
    {
        cout << "Invalid total number of values." << endl;
        cout << "The total number of values must between 3 and 30 values." <<endl;
        cout << "This program will now close..." << endl;
        cout << "Thank you for using this program." << endl;
    }
}

//Function: comupteAverage
//Description: Computes the average of the given inputs.
double computeAverage (double array[], int count)
{
    double sum = 0.0;
    double resultA;
    for (int i =0; i < count; i++)
    {
        sum = sum + array[i];
    }
    resultA = sum / count;
    return resultA;
}
//Function: computeMedian
//Description: Computes the Median of the given inputs.
double computeMedian (double array[], int count)
{
    double resultM;
    if ((count % 2) == 0)
    {
        resultM = (array[count/2] + (array[count/2] -1.0) /2.0);
    }
    else
        resultM = array[count/2];
    return resultM;
}
//Function: computeSTD
//Description: Computes the Standard Deviation of the given inputs.
double computeSTD (double array[], int count, double average)
{
    double temp;
    double sum = 0;
    double resultV;
    for(int i = 0; i < count; i++)
    {
        temp = pow((array[i] - average), 2);
        sum = sum + temp;
    }
    //Account for Sample Standard Deviation N-1
    resultV = sqrt(sum/(count -1));
    return resultV;
}

Номер тестового примера, который я использовал.

73.3
83.4
58
11.9
25.1
69.9
45.7
95.0
44.4
-1.0 // To stop entering values

Thank you in advance for your time and advice!

I performed a shorter test case with only 5 values.

Please enter a value or enter -1.0 to stop entering values
4

Please enter a value or enter -1.0 to stop entering values
3

Please enter a value or enter -1.0 to stop entering values
2

Please enter a value or enter -1.0 to stop entering values
-1.0

-1.0 -92559631349317830000000000000000000000000000000000000000000000.0 -92559631
349317830000000000000000000000000000000000000000000000.0 -9255963134931783000000
0000000000000000000000000000000000000000.0 -1.0 -9255963134931783000000000000000
0000000000000000000000000000000.0 The average is: -61706420899545223000000000000
000000000000000000000000000000000.0
The median is: -1.0
The Standard Deviation is: 53439328075621178000000000000000000000000000000000000
000000000.0
Press any key to continue . . .

Тем не менее, я все еще не понимаю, что заставляет программу вести себя таким образом.

  • 0
    Это не короткий пример кода. Большая часть вашего кода не связана с проблемой. Смотрите sscce.org
  • 1
    Мои извенения! Я разместил весь код, так как понятия не имел, что его вызвало. Позвольте мне сузить это. Спасибо, что держите меня в курсе.
Теги:

1 ответ

0

Во-первых:

for (int i = 0; i < SIZE; i++)
{
    while (number!= SENTINEL)
    {
        cout << "Please enter a value or enter -1.0 to stop entering values" << endl;
        cin >> number;
        array[i] = number;       // <-----
        if (number != SENTINEL)
        {
            count++;
        }

    }
}

вы заполняете только первый элемент array, потому что вы не увеличиваете i. Правильный код должен выглядеть следующим образом:

count = 0;
do
{
    cout << "Please enter a value or enter -1.0 to stop entering values" << endl;
    cin >> number;
    if ( number != SENTINEL )
    {
        array[ count ] = number;
        count++;
    }
}
while ( number != SENTINEL && count < SIZE );

Второе: где код, который вызывает ваши функции???

В-третьих: ваши computeAverage и computeSTD выглядят хорошо, но что, черт возьми, вы делаете в computeMedian???

Обновление: правильный медианный расчет должен быть таким:

double computeMedian (double array[], int count)
{
    double resultM;
    double * sorted_array = new double[ count ];
    for ( int i = 0; i < count; i++ )
    {
        sorted_array[ i ] = array[ i ];
    }
    std::sort( sorted_array, sorted_array + count );
    if ((count % 2) == 0)
    {
        //resultM = (sorted_array[count/2] + (sorted_array[count/2] -1.0) /2.0); // <-- compare this line
        resultM = ( sorted_array[count/2] + sorted_array[count/2 - 1] ) / 2.0;  // <-- and this
    }
    else
        resultM = sorted_array[count/2];
    delete []sorted_array;
    return resultM;
}

И последнее: я настоятельно рекомендую вам использовать std::vector вместо "raw" массивов.

  • 0
    Здравствуйте! Большое спасибо за ваш совет. Что касается ваших вопросов. Мне пришлось сократить количество показанного кода, чтобы сделать его менее болезненным. (Вызовы модуля работают нормально). Что касается computeMedian, я, к сожалению, не знаю точно, как это сделать, и лучшее, что я мог придумать, это увидеть примеры в Интернете. Если вы можете помочь мне в этом разделе, я был бы признателен.
  • 0
    Посмотрите на ответ Макса Шавабке на этот SO вопрос - stackoverflow.com/questions/2114797/…
Показать ещё 5 комментариев

Ещё вопросы

Сообщество Overcoder
Наверх
Меню