非整数类型数字右移
我有以下代码
#include <iostream>
using namespace std;
int main(){
float f=56.34f;
double d=12.34101;
cout<<(f>>1.0)<<endl;
cout<<(d>>1.0)<<endl;
return 0;
}
,但它不起作用,并且出现此错误:
在函数“int main()”中: 第 7 行:错误:“float”和“double”类型的操作数对二进制“operator>>”无效 编译由于 -Wfatal-errors 而终止。
C/C++ 编译器允许右移吗?我使用的是 Visual Studio 2010。
i have following code
#include <iostream>
using namespace std;
int main(){
float f=56.34f;
double d=12.34101;
cout<<(f>>1.0)<<endl;
cout<<(d>>1.0)<<endl;
return 0;
}
but it doesn't work and there is this error:
In function 'int main()':
Line 7: error: invalid operands of types 'float' and 'double' to binary 'operator>>'
compilation terminated due to -Wfatal-errors.
Is here allowed right shifting in C/C++ compiler? I am using visual studio 2010.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这是因为,在 C++ 移植到量子计算机之前,您无法移动半个位。
换句话说,对于 位移运算符< 没有任何意义/a>
>>
支持浮点操作数。然而。That's because, until C++ gets ported to quantum computers, you can't shift by half a bit.
In other words, it makes no sense for the bitshift operator
>>
to support floating-point operands. Yet.您不能转换非整数类型。这在 C++ 中是非法的。
如果您想要乘以或除以二的幂,那就这样做吧。由于浮点数的表示方式,移位的工作方式与浮点数不同。
如果您确实想移动浮点数的位模式,那么您需要进行一些转换,或使用联合。
但你得到的值完全没有意义(你没有除以 2)。
You cannot shift non-integral types. It is illegal in C++.
If you are looking to multiply or divide by powers of two, then just do that. Shifting doesn't work like that on floating point numbers due to the way they are represented.
If you actually do want to shift the bit pattern of a float, then you'll need to do some casting, or use a union.
But the value you get out is totally meaningless (you aren't dividing by 2).
不,因为浮点数的二进制表示应该是不透明的(并且实际上要除以 2,您应该减少尾数)。请改用
*0.5f
。如果您确实想改变二进制表示形式(如 Quake 平方根),请使用带有
unsigned
的union
。No, because the binary representation of floats should be opaque (and to actually divide it by 2 you should decrement the mantissa). Use
*0.5f
instead.If you really want to shift the binary representation (like in Quake square root), use
union
withunsigned
.为什么要右移双精度?如果您想要的话,可以改为
f / 2.0
。Why do you want to right shift a double? You can
f / 2.0
instead if that's what you want.移位运算符仅针对 C++ 中的整数类型定义。您对
56.34 >> 的结果有何期望? 1.0 无论如何?
Shift operators are only defined for integer types in C++. What would you expect as result from
56.34 >> 1.0
anyway?