当你的逻辑不是浮动会发生什么? [英] What happens when you logical not a float?

查看:101
本文介绍了当你的逻辑不是浮动会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以为这只是返回一个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 。这位前pression E!等同于(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 to bool; its value is true if the converted operand is false and false otherwise. The type of the result is bool.

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 to false; any other value is converted to true. A prvalue of type std::nullptr_t can be converted to a prvalue of type bool; the resulting value is false.

Putting those together, 2.5f is a non-zero value and will consequently evaluate to true, which when negated will evaluate to false. I.e., !a == false.


Regarding C, quoting C99 §6.5.3.3/5:

The result of the logical negation operator ! is 0 if the value of its operand compares unequal to 0, 1 if the value of its operand compares equal to 0. The result has type int. The expression !E is equivalent to (0==E).

I.e. the net result is the same as with C++, excepting the type.

这篇关于当你的逻辑不是浮动会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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