C ++负数比较

时间:2020-06-09 06:17:26

标签: c++

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

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

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

如果您尝试通过显式转换将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;
}

换句话说,为了成功进行比较,比较的两面应该相同。

相关问题