[英]Printing negative numbers created on the fly gives incorrect output in c++
Following code explains a quirk, and I am unable to understand why it is the way it is. 以下代码说明了一个怪癖,但我无法理解为什么会这样。 The comments in the code explain the quirk:
代码中的注释解释了这个怪癖:
#include <iostream>
#include <string>
using namespace std;
int main() {
string a,b;
a = "abc";
b = "def";
// On the fly calculation of diff does not lead to desirable results.
cout<<"a size: "<<a.size()<<" b size: "<<b.size()<<" diff: "<<a.size()-b.size()-1<<endl;
// Following assignment works as expected.
int diff = a.size()-b.size()-1;
cout<<"diff "<<diff<<endl;
for (int i=a.size()-1; i>a.size()-b.size()-1; --i) {
cout<<"running"<<endl;
}
return 0;
}
Here is the output I get: 这是我得到的输出:
a size: 3 b size: 3 diff: 4294967295
diff: -1
a.size()-b.size()-1
Since the size
method returns a size_t
, ie an unsigned value, you're computing 3-3-1 = -1
in an "unsigned space" which gives you a wrong value. 由于
size
方法返回size_t
,即无符号值,因此您正在“无符号空间”中计算3-3-1 = -1
,这将为您提供错误的值。
Try: 尝试:
int(a.size())-int(b.size())-1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.