printf和co如何区分float和double [英] How does printf and co differentiate between float and double

查看:140
本文介绍了printf和co如何区分float和double的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因为它没有强类型,我认为它只是选择了正确的内存大小,并根据参数的类型进行解释。但是float和double都使用%f,而且它们是不同的大小。


我可以看到如何通过将值复制到一个temp和铸造(是这样吗?)促进可能工作
,但它是如何工作scanfs / sscanf?

它不区分。您不可能收到一个 float 作为变量:您提供的任何 float 参数首先被提升为<$ c

6.5.2.2/6定义了默认参数促销,而/ 7则说明默认参数促销适用于尾随参数,即由 ... 表示的可变参数。


它是否适用于scanfs / sscanf?




%f code> scanf 需要一个指向 float 的指针。 %lf 需要指向 double的指针,%Lf 需要指向 long double


指向temp和casting如果你提供了一个float参数,那么这个实现会创建一个类型为double的临时对象,并用float来初始化它价值,并通过这个可变参数。按照定义进行转换是通过使用转换运算符进行的显式转换 - 如果您愿意,可以进行转换,以便读者完全清楚发生了什么,但 float f = 3; printf(%f,f); float f = 3完全相同; printf(%f,(double)f); 。默认参数提升的含义与转换相同。


Since it isn't strongly typed I thought it just picked the right memory size and interpreted it based on the type of argument. But float and double both use %f and they are different sizes.

P.S. I can see how promotion via copying the value to a temp and casting(is this right?) might work but how does it work for scanfs/sscanf?

解决方案

It doesn't differentiate. It's not possible to receive a float as a vararg: any float argument that you provide is first promoted to double.

6.5.2.2/6 defines "default argument promotions", and /7 states that default argument promotions are applied to "trailing arguments", that is varargs denoted by ....

how does it work for scanfs/sscanf?

The %f format for scanf requires a pointer to float. %lf requires a pointer to double, %Lf requires a pointer to long double.

copying the value to a temp and casting(is this right?)

If you provide a float argument, then the implementation creates a temporary of type double, initializes it with the float value, and passes this as the vararg. Casting by definition is explicit conversion by use of the cast operator -- you can cast if you like in order to make it exactly clear to the reader what's going on, but float f = 3; printf("%f", f); is exactly the same as float f = 3; printf("%f", (double)f);. The default argument promotion has the same meaning as the cast.

这篇关于printf和co如何区分float和double的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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