Other answers have suggested changing the value of pi slightly.
Other answers have suggested changing type float
to type double
.
Both of these suggestions move the problem around slightly, perhaps changing the objectionable displayed value of -0 to plain 0.
(And switching from float
to double
is almost always a good idea, no matter what.)
But none of these suggestions actually "solve" this particular "problem", because fundamentally there is no actual problem here.
The real issue, as I said in a comment, is that it is just not possible to compute the cosine of 90.0000000000 degrees, at all, because you are never going to be able to represent the value π/2 perfectly accurately in radians. You're inevitably always going to be working with the equivalent of 89.9999999999 degrees, or 90.0000000001 degrees, so to speak. That is, the problem isn't that cos()
is computing the wrong value; the problem is that you're not even passing it the "right" value to begin with! And when π/2 comes out a little bit over, meaning that cos()
ends up computing a value like -0.0000000001, a high-quality version of printf
is going to round and display it as -0, because -0 is a thing in computer floating point.
If you have a "fixed" version of the original program that no longer displays cos(90) as -0, I suggest trying it with cos(-90), or cos(270) — I bet one or the other of those will display -0, so you're right back out of the frying pan and into the fire again.
If you have a requirement that says you must never display "-0", I believe you would want to pursue a completely different approach, perhaps something along the lines of
char tmp[50];
snprintf(tmp, sizeof(tmp), "%f", result);
if(*tmp == '-' && atof(tmp) == 0) result = -result;
printf("result = %f\n", result);
It may seem strange to be tinkering around with the string representation like this, but it actually makes sense, because it's only after converting (and perhaps rounding) to a string representation that we can be sure we've got the "-0.000000" case that needs special attention.