I was writing a program to calculate negative powers of 2.
I used the following two code snippets:
cout.precision(3);
cout << scientific << pow(2.0, p) << endl;
AND
ans = pow(2.0, p);
printf("%.3e\n", ans);
For p = -8271, the cout gives the right answer (1.517e-2490) but I get a widely different answer for the printf (6.929e-310). Why does this discrepancy occur?
I use Codeblocks on Ubuntu.
I bet that’s because
ansis along double, but you didn’t tellprintfto expect along double. The format code you want is%.3Leassuming that’s the case.The g++ compiler even has a warning to detect format/parameter mismatches (I think it comes with
-Wall) but I always prefer iostreams because they’re type safe like this.All this is of course assuming that
pis alsolong double, causing the compiler to pick thelong doubleversion ofpow.