I have been hacking at this for days and the issue is our professor is not letting use cmath.
So his instructions for calculating the square root is to use a certain formula and I cant get it to work. It is defined at the bottom as a function called sqrt
I can enter values and get the variance but i dont see how to 'join' the 2 sections and to have this function calculate the square root of the variance.
#include<iostream>
usingnamespace std;
double sqrt(double value);
int main()
{
int n = 0 ; //enter number of values
char c = 'y';
while(c == 'y' || c == 'Y') //while it is a yes to run the loop
{
while(n > 100 || n <= 0)
{
cout<<"How many values do you wish to enter? (Less than 100)"<<endl; //enter number of numbers to enter
cin >> n;
}
int i = 0;
int array[100];
while(i<n)
{
cout<<"Enter number "<<(i+1)<<endl; //enter numbers
cin>>array[i];
i++;
}
double mean = 0;
for( i = 0; i<n ; i++)
{
mean += array[i]; //add all values
}
mean /= n; //find mean
double variance = 0;
double std_dev = 0;
for( i = 0; i<n ; i++)
{
variance += (array[i] - mean)*(array[i] - mean); //calculate sum of squares
}
variance /= n; //calculate variance
std_dev = sqrt(variance); //get sqrt of it to get standard deviation
cout<<"Variance: "<<variance <<" and Standard deviation: "<<std_dev<<endl;
cout<<"Do u wish to continue? Enter 'y' or 'Y' for yes and 'n' or 'N' for no"<<endl;
cin >> c;
}
}
double sqrt(double value)
{
double new_value;
double old_value = 1; //set seed to 1 initially
new_value = 0.5*(old_value + (value/old_value)); //set new value using this formula
while(new_value - old_value >= 0.005) //while difference netween new value and old value >= 0.005
{
new_value = 0.5*(old_value + (value/old_value)); //keep calculating new_value
old_value = new_value; //set old_value to this new value
}
return new_value;
}
yes, the variance works but the std deviation is not calculating properly. I am getting a large number.
So basically line 40 is calling the sqrt function but not giving me a proper answer.
If I try to use the variance variable in the sqrt function, the compiler calls an error as it is only defined in the Main function. That is what I mean by tying the 2 together.
so upon further inspection the formula seems to just be returning a value half of the variance, not the square root. However the formula came from the teacher.