【问题标题】:c++ negative number comparison [duplicate]c ++负数比较[重复]
【发布时间】:2020-09-28 06:04:49
【问题描述】:

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

#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.length()返回的类型,然后检查将这种类型与intmax的类型)进行比较时会发生什么
  • -1 转换为 unsigned 的值会产生类似于正 40 亿的值。你不是在比较负数!

标签: c++


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2013-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-28
      • 1970-01-01
      • 2018-04-26
      • 2018-07-09
      相关资源
      最近更新 更多