C++ 负数比较

c++ negative number comparison

本文关键字:比较 C++      更新时间:2023-10-16

为什么下面的代码给出正确的输出

#include <iostream>
#include <string>
using namespace std;
int main()
{
int max=0;
string k ="hello";
if(k.length()>max){
max = k.length();
}
cout<<max;
}

但是下面的代码没有?

#include <iostream>
#include <string>
using namespace std;
int main()
{
int max=-1;
string k ="hello";
if(k.length()>max){
max = k.length();
}
cout<<max;
}

这可能是由于类型转换。您的最大值可能会转换为无符号,因为 k.lenght 是无符号的。

如果您尝试通过显式转换将maxk.length()进行比较,它将起作用。

k.length()unsigned long long返回你,但maxsigned int。这可能是错误的原因。为了解决这个问题,让我们做这样的事情:

请看以下内容:

#include <iostream>
using namespace std;
int main()
{
int max = -1;
string k ="hello";
if(int(k.length()) > max) // use int()
max = k.length();
cout << max;
}

换句话说,比较的双方应该相同才能成功进行比较。