Using C The root mean square is a specific kind of average w
Using C++:
The root mean square is a specific kind of average which is used for various purposes. This means that a sequence of values is squared and summed, then divided by the count of the values; the entire calculation is then square-rooted. Ask the user for input; stop when the user enters -1. Be sure to use the square and squareRoot functions:
float squareRoot (float s) {
float xn;
if (s == 0.0) {
return 0.0;
}
xn = s/2.0;
int counter = 1;
while (counter <= 10) {
xn = (xn + (s/xn))/2.0;
counter = counter + 1;
}
return xn;
}
and
int square (int what) {
int answer = what * what;
return answer;
}
Solution
#include <iostream>
using namespace std;
float squareRoot (float s) {
float xn;
if (s == 0.0) {
return 0.0;
}
xn = s/2.0;
int counter = 1;
while (counter <= 10) {
xn = (xn + (s/xn))/2.0;
counter = counter + 1;
}
return xn;
}
int square (int what) {
int answer = what * what;
return answer;
}
int main()
{
//declare variables
bool flag=true;
int value=0;
float sum=0;
int cnt=0;
//prompt the user until -1 is entered
do
{
//prompt user for value
cout<<\"Enter a value: \";
cin>>value;
//check if user is -1,exit
if(value==-1)
flag=false;
else
{
//increment no of numbers
cnt++;
//find square root of nos and add to sum
sum+=square(value);
}
}while(flag);
//divide sum by total no of numbers inputted
sum=sum/cnt;
//find square root of sum value
sum=squareRoot(sum);
//display RSM
cout << \"Root Mean Square Root of \" <<value<<\" is \"<<sum<< endl;
return 0;
}
Sample output:
Enter a value: 2
Enter a value: 5
Enter a value: 8
Enter a value: 9
Enter a value: 4
Enter a value: -1
Root Mean Square Root of -1 is 6.16

