std :: cout如何在一个补码系统中输出负零? [英] How does std::cout print negative zero in a ones-complement system?
问题描述
在一个补码平台上,以下代码将输出什么?
On a ones-complement platform, what would the following code print?
#include <iostream>
int main() {
int i = 1, j = -1;
std::cout << i+j << std::endl;
return 0;
}
我怀疑它会打印"0"而不是"-0",但是我似乎找不到任何权威.
I would suspect it would print "0" instead of "-0", but I can't seem to find anything authoritative.
为澄清起见,我对如何打印-0感兴趣,一些人建议在实践中,使用上述代码的情况下,ones-compliment的实现可能不会产生负零.
To clarify, I am interested in how -0 would be printed, several people have suggested that in practice, the implementation of ones-compliment might not generate a negative zero with the above code.
在这种情况下,建议使用以下代码实际生成-0:
In those cases, the following has been suggested to actually generate a -0:
#include <iostream>
int main() {
std::cout << ~0 << std::endl;
return 0;
}
问题仍然存在:这将打印什么?
The question still remains: what will this print?
推荐答案
首先,为了说明问题,先使用按位运算来生成负零,然后再使用结果值是不可移植的.就是说,在 fprintf
的文档中(因此,在 std :: basic_ostream :: operator<<(int)
的文档中)没有指定符号是否代表int对应于 unsigned
表示形式中的填充位或实际值位.
First of all, just to clarify thing, crafting a negative zero using bitwise operations and then using the resulting value is not portable. That said, nothing specifies in the documentation of fprintf
(thus, of std::basic_ostream::operator<<(int)
) whether the sign bit in the representation of int corresponds to a padding bit in the representation of unsigned
or an actual value bit.
结论是,这是未指定的行为.
As a conclusion, this is unspecified behaviour.
#include <iostream>
int main() {
std::cout << ~0 << std::endl;
return 0;
}
这篇关于std :: cout如何在一个补码系统中输出负零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!