在c++中打印动态创建的负数会导致不正确的输出

Printing negative numbers created on the fly gives incorrect output in c++

本文关键字:不正确 输出 打印 动态 创建 c++      更新时间:2023-10-16

下面的代码解释了一个怪癖,我无法理解为什么它是这样的。代码中的注释解释了这个怪癖:

#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;
}

下面是我得到的输出:

a size: 3 b size: 3 diff: 4294967295
diff: -1
a.size()-b.size()-1

由于size方法返回size_t,即无符号值,您在"无符号空间"中计算3-3-1 = -1,这会给您一个错误的值。

试题:

int(a.size())-int(b.size())-1