I made a simple code to process the root mean square of a sequence of user entered variables. It works for that task but I cannot figure out how to specify that no data is available for values less than 0.
-1 stops the prompt and starts the calculation. If -1 or -2 is the first input I need it to display "No data" and stop like this:
The program will display "No data", with any negative number, and will NOT add it to nSum. I used any negative number only because in your post, you mention -1 or -2 as input.
// Root Mean Square.cpp : Defines the entry point for the console application.
//
#include <iostream>
#include <cmath>
usingnamespace std;
int main()
{
double nSum = 0, counter = 0, nDivide, rms, number;
number = 0.0;
while ( number >= 0) //loop to gather positive numbers from user. Stops if negative is entered
{
cout << "Enter a positive number (-1 exits): ";
cin >> number;
counter++;
if ( number >=0)
{
double nSquare = number*number; //squares user numbers and adds them to get the sum
nSum += nSquare;
nDivide = nSum/counter;
rms = sqrt(nDivide);
cout << "Answer = " << rms << endl;
}
}
cout << endl << endl << "No data" << endl << endl;
}
Thank you the while loop fixed the No data problem perfect. How would I modify it to only display "Answer = " and the rms after the user enters a negative number?
Right now it is printing the rms after each number is added by the user until they enter a negative number.
I tried moving the cout << "Answer = " << rms << endl; out of the loop and moving the calculations
Hello still having no luck with it, it displays the root mean sum calculation after each user entry. I tried adding an else if statement but that did not fix it either.
// Root Mean Square.cpp : Defines the entry point for the console application.
//
#include <iostream>
#include <cmath>
usingnamespace std;
int main()
{
double nSum = 0, nDivide, rms, number;
number = 0.0;
int counter = 0;
double nSquare;
while ( number >= 0) //loop to gather positive numbers from user stops if -1 is entered
{
cout << "Enter a positive number (-1 exits): ";
cin >> number;
counter++;
if ( number >=0)
{
nSquare = number*number; //squares user numbers and adds them to get the sum
nSum += nSquare;
nDivide = nSum/counter;
rms = sqrt(nDivide);
}
}
cout << endl << endl << "No more Data.." << endl;
cout << "Final answer = " << rms << endl;
}