In one of my c++ class assignments, I was given the task:

Write a program that reads in a list of floating-point numbers and then prints out the count of the values, the average, and the standard deviation.

You can assume that the the user's input is always valid and that the list contains at least two numbers.

You can assume that the numbers in the list are separated by one space character and that the character following the last number in the list is the newline character.

Implement a loop in which the above actions are repeated until the user requests to quit.

I am struggling with the last step, where I need to ask the user if they want to continue. My code is as follow.


#include <iostream>
#include <algorithm>
#include <string>
#include <cstdlib>

using namespace std;
int main()
{ 

    char counter;



    do {
        char ch = ' ';

        int i = 0;

        double sum = 0; 

        double average = 0; 

        double sum_squared = 0;

        cout << "Please enter a list of values (of type double): ";

        do {

            double x;

            cin >> x;

            ch = cin.get();

            i += 1;

            sum += x;

            double x_squared = pow(x, 2);

            sum_squared += x_squared;

        } while (ch != '\n');

        average = sum / i;

        double standard_deviation = sqrt((sum_squared - (pow(sum, 2) / i)) / (i - 1));

        cout << "Number = " << i << endl;

        cout << "Average = " << average << endl;

        cout << "Standard deviation = " << standard_deviation << endl;

        cout << "Continue? (y,n) "; cin >> counter;



    } while (counter = 'y');
    return 0;
}

I was expecting that when user enter y in the end, the program would re-execute. But it turned out to be weird. When I enter n, the code still re-execute. Can anyone explain why? Additionally, how do I correctly implement this function to my code? Thank you all for your help and response.

1 Answers

1
Community On Best Solutions

changing

counter = 'y'

to

counter == 'y'

near the end will yield the satisfactory result.