Kraig said:
John,
Perhaps that is part of my problem. I lack an understanding of how to
calculate pi using numbers of terms that are powers of 2 in C++, in the
most effective manner.
I do know I need a loop. However, I left it out because I feel it's
better to calculate pi properly, then move on to looping/incrementing
the terms. I hope that makes sense, John. Thank you for your help - it
is invaluable!
kraig
I do this with a calculator when I'm bored in school.
Here is a main() function for calculating the first terms.
I'm using double instead of float because many of the library
functions use double. See the C++ FAQ below.
int main(void)
{
double result = 0;
const double numerator = 4.0;
double denomenator = 1.0;
const unsigned int num_terms = 4;
/* Note that the first term has an implied denomenator
* of 1 (one).
*/
// result = 0.0 + (4.0 / 1.0)
result = result + numerator / denomenator;
cout << "Denomenator: " << denomenator;
cout << ", Result: " << result << endl;
/* In generating the next term, the denomenator is
* incremented by 2.
* The sign of the term changes to negative, IOW
* the next term will be subtracted.
*/
// result = result - (4.0 / 3.0)
denomenator += 2;
result = result - numerator / denomenator;
cout << "Denomenator: " << denomenator;
cout << ", Result: " << result << endl;
/* As the pattern goes, increment the denomenator by
* two, then add in the next term:
*/
denomenator += 2;
result = result + numerator / denomenator;
cout << "Denomenator: " << denomenator;
cout << ", Result: " << result << endl;
denomenator += 2;
result = result - numerator / denomenator;
cout << "Denomenator: " << denomenator;
cout << ", Result: " << result << endl;
return 0;
}
There is a pattern to the above code. Which results in:
int main(void)
{
double result = 0;
const double numerator = 4.0;
double denomenator = 1.0;
const unsigned int num_terms = 4;
for (unsigned int i = 0;
i < num_terms / 2; // Two terms per loop.
i += 2)
{
result += numerator / denomenator;
cout << "Denomenator: " << denomenator;
cout << ", Result: " << result << endl;
denomenator += 2;
result -= numerator / denomenator;
cout << "Denomenator: " << denomenator;
cout << ", Result: " << result << endl;
denomenator += 2;
}
return 0;
}
Your challenge, should you accept it, is to alter the
loop so that it can handle any number of terms, not
just multiples of two. For example, set the
constant "num_terms" to 7.
After you have that working, add in the I/O to
prompt the user for the number of terms. Remember
to validate the user's input (for example, -2
for the quantity doesn't work).
The final revision is to make the program print the
output per the requirements.
--
Thomas Matthews
C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq:
http://www.parashift.com/c++-faq-lite
C Faq:
http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.learn.c-c++ faq:
http://www.comeaucomputing.com/learn/faq/
Other sites:
http://www.josuttis.com -- C++ STL Library book