Hello everyone, I just starting to learn c++ and I've come across a problem. While looking over my friends c++ calculator I tried to make my own. After I completed it sadly it didn't run... Then after 30 minutes of debugging I got to the point I'm at right now. I can run the program without a pow but it comes up with the completely wrong answer and If i try to put the pow in it fails to compile and gives me this error

[code]1>.\PI-TRIG.cpp(17) : error C2661: 'pow' : no overloaded function takes 1 arguments[/code]

my C++ code is as follows..

[code] #include <iostream>

#include <math.h>

#define NUM_OF_ELEMENTS 20000using namespace std;

int main()

{

double long pi = 0;

// Calculating pi/4

for (long int n = 1; n <= NUM_OF_ELEMENTS; n++)

{

pi += (double long) pow((-1)^(n-1))/(2*n-1);

}

// Calculating pi

pi *= 4;

cout << "Estimated PI value (" << NUM_OF_ELEMENTS << " elements of Leibnitz series): "<< pi << endl << endl;

system("pause");

return 0;

}

[/code]Anyways if you have any idea on how to fix it or make the formula more accurate or just overall make it better code I'm open for suggestion in fact I really hoping they come =)

#include <math.h>If you're using C++ rather than C, you should #include <cmath> instead.

#define NUM_OF_ELEMENTS 20000Another hangover from C. In C++ the following is more idiomatic:

const int numElements = 20000;

double long pi = 0;I'm more used to seeing it written as "long double".

for (long int n = 1; n <= NUM_OF_ELEMENTS; n++)An int would suffice for at least 32767 elements on all platforms, and on most of today's platforms at least 2147483647, so no need for long int.

pow((-1)^(n-1))I think the error message gives you a good clue as to what is wrong here. pow requires two arguments. You are only passing one. The ^ operator does not mean "raise to the power of". It means "bitwise exclusive or". Something completely different to what you want to do.

You should also think about performance. The pow function is typically implemented by taking the logarithm, multiplying by the power and taking the antilogarithm of the result. That is very time-consuming for the very simple purpose you are putting it to, which is to alternate the sign of each term in your sequence.

system("pause");This would only work on DOS or Windows. What if you tried your application on Linux or Solaris?

Finally, there is a "cheat" to make the result more accurate: add only half of the last term. (This trick only works for terms with alternating signs, like this one.)

Ask Your Question

Weekly Poll

Would you ride in a self-driving car from Tesla?

Discuss in The Lounge

Poll History