I am working on an assignment that is due in a couple days although my program is not acting as I expected it to and I was hoping someone here could help me. Here is the code I have so far:
/*
Programmer: John Lee
Date: October 11, 2008
Objective: To determine how many terms of the infinite equation "pi=4-(4/3)+4(5)-4(7)..." are needed to calculate the value of pi accurately.
*/
#include <iostream>
#include <cmath>
usingnamespace std;
int main()
{
while(1)
{
int count=1;
float pi, sum=0, temp;
cout<<"Enter a value of pi:"; //value of pi is entered
cin>>pi;
while(abs(sum-pi) < 0.0005) //precision check
{
if((count%2)==0) //even numbers
{
temp=((2*count)-1);
sum=sum -(4 / temp);
count++;
}
else //odd numbers
{
temp=((2*count)-1);
sum=sum -(4 / temp);
count++;
}
}
cout<<"The number of terms needed is "<<--count<<" to calculate the value of "<<pi<<".\n\n";
}
return 0;
}
The inteded purpose of this program is to caclulate the number of terms of the formula required to calculate the value of pi as entered by the user. The nested while loop runs... but always returns count as 1 which then becomes 0 on the output. Can anyone see any obvious way to fix this?
What do you mean by "numbers with comma"? The problem I see in changing count to a different type such as a float is that then my modulus won't work and I wont have any way to differ between even and odd :S.
>.<" Just seen one thing >> It's not count that makes your code not work correctly... But in this case, I not have any idea about why it not does work correctly >.>"
What are you expecting to get if the number you are assigning to count is 1.
This test while(abs(sum-pi) < 0.0005) is never true, since sum = 0 and pi is a number bigger than 0.0005.
Now, if you change this while(abs(sum-pi) < 0.0005) to while(abs(sum-pi) > 0.0005) the program will still give you nothing, because both test have the same conclusion
int main()
{
while(1)
{
int count=1;
float pi, sum=4, temp;
cout<<"Enter a value of pi:"; //value of pi is entered
cin>>pi;
while(abs(sum-pi) > 0.0005) //precision check
{
if((count%2)>0) //odd numbers
{
temp=((2*count)+1);
sum=sum -(4 / temp);
count++;
}
else //even numbers
{
temp=((2*count)+1);
sum=sum +(4 / temp);
count++;
}
}
cout<<"The number of terms needed is "<<count<<" to calculate the value of "<<pi<<".\n\n";
}
return 0;
}
I have it so that it is displaying numbers other than one now :). Although what I need to do now is change the precision check so that it will work for more precise values of pi. The precision check given for 3.14 is within 0.0005. Is there a way to sense the number of digits entered by the user and use that in a formula for the precision check? something like (0.05*pow(10,n)) would work nicely if I could automate the digit processing.