Incorrect result printed when multiplying numbers in C
I've recently begun using C and I'm having some problems with the simple arithmetic operation of just being able to multiply two numbers.
Initially, I tried to print the result of 8 * 2 to a file. Currently this outputs 16. Next, I multiplied what I really wanted 8*0.000000123456789. Here is my code:
fprintf( fp2, "%d\n", (long double)(8*0.000000123456789));
The result outputted to the file is : -1086490624. W开发者_如何学JAVAhereas really it should have been : 0.000000987654312. I intentionally type-casted the arithmetic as a long double to prevent any overflow. Not doing anything and using:
fprintf( fp2, "%d\n", (8*0.000000123456789));
Yields 1719134127, again having no relation to the actual value of 0.000000987654312
Any suggestions please?
I believe that your problem is that you're using the %d
placeholder in printf
, which only prints out int
values. Since you're passing a double
or long double
to printf
, you probably want to use another modifier in place of %d
. For example, if you're printing out a double
, you could use the %f
modifier:
fprintf( fp2, "%f\n", (8*0.000000123456789));
The more technical reason that you're getting random values back instead of anything close to the original value is that when you try printing something with printf
, the function tries interpreting the bits of the argument in a way that depends on what specifier you use. Since floating-point values like float
s and double
s are usually represented internally in the computer using a completely different encoding than integers (often as IEEE-754 values rather than signed two's complement), the results of trying to take bits of a float
or double
and representing them as an integer are usually meaningless.
Hope this helps!
Suggestion 1: Read the manual for printf
.
Suggestion 2: Repeat to yourself over and over: "printf is not typesafe. I promise to be extra careful when using it."
Suggestion 3: Always always enable and take to heart all compiler warnings. This would have caught it right away.
Answer: You promise printf
that you will provide an int
by saying %d
. However, in reality you provide a long double
. The result of this failure to keep your promise is undefined behaviour. To print a long double, say %Lf
(cf. (1)).
精彩评论