Reputation: 359
Most likely a really simple question, please keep any answers easy to understand I'm still quite new at this:
I'm making a little app, and I need to use powers for a couple of calculations. After a little research I found the pow function in cmath, and have had a play. In the end i came up with this snipped, which works:
#include <iostream>
#include <cmath>
using namespace std;
int main ()
{
float dummy2, test(6.65);
dummy2 = (float) pow((float) 3.57, test);
cout << dummy2;
return 0;
}
and it returns the correct answer (4734.17), but only to two decimal places. I want 5 decimal places preferably.
What did I do wrong here? Am I using the wrong data type (floats)? Or is it a limit of whatever is in the pow function to using only 2dp?
I could, if it came to it just define constants with the values i want, since it's only going to be 4 or 5 sums that I need this precision on, but if it's possible to have the program calculate it that would be great.
Thanks
Upvotes: 0
Views: 4413
Reputation: 28665
I would do as fbinder says, and use Doubles for greater precision. To solve your problem, you have two options, C-style and C++ style.
C-Style
#include <cstdio>
printf("%.5f", dummy2);
C++ Style
#include <iomanip>
std::cout << setprecision(5) << dummy2 << std::endl;
OR
std::cout.precision(5);
std::cout << dummy2 << std::endl;
// continue to use cout to output 5 decimal places
Upvotes: 6
Reputation: 13214
For a better precision you should use double. Doubles has 15 digits of precision against 7 for floats.
Upvotes: 3