使用 printf 打印出浮点值 [英] using printf to print out floating values

查看:35
本文介绍了使用 printf 打印出浮点值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#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;
}

ff = %f 的输出不是预期的.

The output for ff = %f is not expected.

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

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

这段代码的重点是显示如果浮点值用 %d 打印而int 值用 %f 打印会发生什么.

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.

为什么即使我使用 %f 也不能正确打印浮点值?

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

推荐答案

printf() 不是类型安全的.

您传递给 printf() 的参数将根据对编译器的承诺进行处理.

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

此外,当通过可变参数传递时,floats 被提升为 doubles.

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

因此,当您第一次向编译器 %f 承诺时(对于 xf),编译器会吞噬整个 double(通常为 8字节)从参数,在这个过程中吞下你的浮点数.然后第二个 %f 直接切入第二个双精度数的零尾数.

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.

这是您的论点图片:

+-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------|

但是f看起来像这样(已经被提升为double):

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  |

注意 1073217536 是 0x3FF80000.

Note that 1073217536 is 0x3FF80000.

这篇关于使用 printf 打印出浮点值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆