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. Whereas 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
%dplaceholder inprintf, which only prints outintvalues. Since you’re passing adoubleorlong doubletoprintf, you probably want to use another modifier in place of%d. For example, if you’re printing out adouble, you could use the%fmodifier: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 likefloats anddoubles 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 afloatordoubleand representing them as an integer are usually meaningless.Hope this helps!