C++ 负数比较
c++ negative number comparison
为什么下面的代码给出正确的输出
#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 是无符号的。
如果您尝试通过显式转换将max
与k.length()
进行比较,它将起作用。
k.length()
会unsigned long long
返回你,但max
signed 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;
}
换句话说,比较的双方应该相同才能成功进行比较。
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 为什么比较运算符如此快速
- 我可以使用 g++ 进行三种比较 (<=>) 吗?
- 比较字符数组
- 将模板化的类型与C++中的某些类/类型进行比较
- C++自定义比较函数
- 如何比较自定义类的std::变体
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- std::设置自定义比较器
- 布尔比较运算符是如何在C++中工作的
- C++将目录中的所有文件与::filesystem进行比较
- shell排序中的交换和比较
- 如何在C++中比较两个char数组
- catch框架有没有办法比较流或文件
- 从文件中读取多个字节,并将它们存储在C++中进行比较
- 智能指针作为无序映射键,并通过引用进行比较
- 比较if语句中的数组值和int值
- 对于循环变体比较
- 使用自定义比较函数使用std::sort()对矢量字符串进行排序时出现问题
- 比较两个大小不等的映射c++