本文介绍了比较签名与未签名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,


我什么时候应该担心签名与未签名的比较

整数?有人能给我一个例子,这样的比较会导致

不想要的结果吗?


谢谢,

Tim。

Hi all,

When should I be worried about doing a comparison of signed vs unsigned
ints? Could someone give me a example where such a comparison would lead to
unwanted results?

Thanks,
Tim.

推荐答案




#include< iostream>


int main()

{

int a = -100;

unsigned int b = 100;

std :: cout<< a<< "是

<< (a< b?""" not not)<< "少于 << b<< ''\\ n'';

}



#include <iostream>

int main()
{
int a = -100;
unsigned int b = 100;
std::cout << a << " is "
<< (a < b ? "" : "not") << " less than " << b << ''\n'';
}




#include< iostream>

int main()
{
int a = -100;
unsigned int b = 100;
std :: cout<< a<< "是
<< (a< b?""" not not)<< "少于 << b<< ''\\ n';;
}



#include <iostream>

int main()
{
int a = -100;
unsigned int b = 100;
std::cout << a << " is "
<< (a < b ? "" : "not") << " less than " << b << ''\n'';
}




另一个例子:


#include< iostream>


int main()

{

int a = -1;

unsigned int b = std :: numeric_limits< unsigned int> :: max();

std :: cout<< a<< "是 << (a == b?"":" not")

<< "等于 << b<< ''\\ n'';

}



Another example:

#include <iostream>

int main()
{
int a = -1;
unsigned int b = std::numeric_limits<unsigned int>::max();
std::cout << a << " is " << (a == b ? "" : "not")
<< " equal to " << b << ''\n'';
}





谢谢Rolf!



Thanks Rolf!


这篇关于比较签名与未签名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 09:10