Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
375 views
in Technique[技术] by (71.8m points)

c - using printf to print out floating values

#include<stdio.h>
#include<stdlib.h>

int main(void)
{
  int x, *ptr_x;
  float f , *ptr_f;

  ptr_f = &f;
  ptr_x = &x;
  *ptr_x = 5;
  *ptr_f = 1.5; //printf("%d %f
", f,x);

  printf ("

xd = %d  xf = %f 
 ff = %f  fd = %d", x,x,f,f);
  return 0;
}

The output for ff = %f is not expected.

xd = 5 xf = 0.000000
ff = 0.000000 fd = 1073217536

The point of the this code is to show what would happen if a floating value is printed with %d and if a int value is printed %f.

Why is the float value not being printed properly even if i use %f ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

printf() is not typesafe.

The arguments that you pass to printf() are treated according to what you promise the compiler.

Also, floats are promoted to doubles when passed through variadic arguments.

So when you promise the compiler %f the first time (for xf), the compiler gobbles up an entire double (usually 8 byte) from the arguments, swallowing your float in the process. Then the second %f cuts right into the zero mantissa of the second double.

Here's a picture of your arguments:

+-0-1-2-3-+-0-1-2-3-+-0-1-2-3-4-5-6-7-+-0-1-2-3-4-5-6-7-+
|    x    |    x    |        f        |        f        |
+---------+---------+-----------------+-----------------+

%d--------|%f----------------|%f---------------|%d------|

But f looks like this (having been promoted to double):

f = 3FF8000000000000

Let's draw it again with values, and speculating about your machine endianness:

| 05000000 | 05000000 | 00000000 0000F83F | 00000000 0000F83F |
| %d, OK   | %f, denormal...    | %f, denormal...   | %d, OK  |

Note that 1073217536 is 0x3FF80000.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...