为什么printf的打印错误的价值观? [英] Why does printf print wrong values?

查看:129
本文介绍了为什么printf的打印错误的价值观?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我得到错误的值时,我打印 INT 使用的printf(%F \\ N,为mynumber)

我不明白为什么它打印罚款与%d个,但不能与%F 。难道不应该只是添加额外的零?

  int类型的= 1;
INT B = 10;
INT C = 100;
INT D = 1000;
INT E = 10000;的printf(%d个%D%D \\ n,A,B,C,D,E); //输出精
的printf(%F%F%F%F%F \\ N,A,B,C,D,E); //打印奇怪的东西


解决方案

嗯,当然它打印怪异的东西。您传递 INT S,但告诉的printf 您在通过浮动秒。由于这两个数据类型有不同的和不兼容的内部重新presentations,你会得到胡言乱语。

有没有自动投当你通过变量如的printf A variandic功能,值传递给函数的数据类型,它们实际上是(或升级在某些情况下一个较大的兼容型)。

你做了什么有点类似这样的:

 工会{
    INT N;
    浮F;
} X;x.n = 10;的printf(%F \\ N,x.f); / *传递二进制重新presentation 5,
                        但对待同样的位模式为float,
                        即使它们是不兼容的* /

Why do I get the wrong values when I print an int using printf("%f\n", myNumber)?

I don't understand why it prints fine with %d, but not with %f. Shouldn't it just add extra zeros?

int a = 1;
int b = 10;
int c = 100;
int d = 1000;
int e = 10000;

printf("%d %d %d %d %d\n", a, b, c, d, e);   //prints fine
printf("%f %f %f %f %f\n", a, b, c, d, e);   //prints weird stuff

解决方案

well of course it prints the "weird" stuff. You are passing in ints, but telling printf you passed in floats. Since these two data types have different and incompatible internal representations, you will get "gibberish".

There is no "automatic cast" when you pass variables to a variandic function like printf, the values are passed into the function as the datatype they actually are (or upgraded to a larger compatible type in some cases).

What you have done is somewhat similar to this:

union {
    int n;
    float f;
} x;

x.n = 10;

printf("%f\n", x.f); /* pass in the binary representation for 5, 
                        but treat that same bit pattern as a float, 
                        even though they are incompatible */

这篇关于为什么printf的打印错误的价值观?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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