当你的逻辑不是浮动会发生什么? [英] What happens when you logical not a float?
问题描述
我以为这只是返回一个int。还有什么事情我应该知道的? C / C ++区别在哪里?
浮动= 2.5;
!一个; //这是什么回报?诠释?浮动?
对于C ++,引用C ++ 11§5.3.1/ 9:
逻辑否定运算符的操作数
的上下文转换为
布尔
!;它的值是真正
如果转换的操作数是假
和假
其他。结果类型是布尔
。
块引用>那么,什么是的真正的相关这里是行为
的static_cast<布尔>(some_float)
&ndash的;报价§4.12/ 1:
算术,无范围枚举,指针,或指针到成员A型prvalue可以转换为类型的prvalue
布尔
。零值,空指针值或空成员指针值转换为假
;任何其他的值转换为真正
。类型的prvalue的std :: nullptr_t
可转换为类型的prvalue布尔
;结果值假
。
块引用>把这些在一起,
2.5F
是一个非零值并将因此计算为真正
,当其否定的结果都将为假
。即,!一个
==假
。对于C,报价C99§6.5.3.3/ 5:
逻辑否定运算符的结果
!
是0
如果操作数的值进行比较,不等于0
,1
0 > 。结果类型INT
。这位前pressionE!
等同于(0 == E)
。
块引用>即。最终结果是一样的使用C ++,除的类型。
I assume this just returns an int. Is there anything else going on I should be aware of? C/C++ differences?
float a = 2.5; !a; // What does this return? Int? Float?
解决方案Regarding C++, quoting C++11 §5.3.1/9:
The operand of the logical negation operator
!
is contextually converted tobool
; its value istrue
if the converted operand isfalse
andfalse
otherwise. The type of the result isbool
.So what's really relevant here is the behavior of
static_cast<bool>(some_float)
– quoting §4.12/1:A prvalue of arithmetic, unscoped enumeration, pointer, or pointer to member type can be converted to a prvalue of type
bool
. A zero value, null pointer value, or null member pointer value is converted tofalse
; any other value is converted totrue
. A prvalue of typestd::nullptr_t
can be converted to a prvalue of typebool
; the resulting value isfalse
.Putting those together,
2.5f
is a non-zero value and will consequently evaluate totrue
, which when negated will evaluate tofalse
. I.e.,!a
==false
.
Regarding C, quoting C99 §6.5.3.3/5:
The result of the logical negation operator
!
is0
if the value of its operand compares unequal to0
,1
if the value of its operand compares equal to0
. The result has typeint
. The expression!E
is equivalent to(0==E)
.I.e. the net result is the same as with C++, excepting the type.
这篇关于当你的逻辑不是浮动会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!