zoukankan      html  css  js  c++  java
  • 记录一个奇妙的Bug, -1 >= 2 ?

    直接上代码:

    #include <iostream>
    #include <vector>
    
    using namespace std;
    
    
    int main()
    {
    	vector<string> vctStr;
    	vctStr.push_back("Hello");
    	vctStr.push_back("World");
    
    	cout<<"VctSize: "<<vctStr.size()<<endl;    // VctSize: 2
    
    	int iType = -1;
    
    	if (iType >= vctStr.size() )
    	{
    		cout<<"Amazing ……"<<endl;			// -1 竟然大于2 ?!
    		cout<<"iType: "<<iType<<", size: "<<vctStr.size()<<endl;
    		
    	}
    	
    	return 0;
    }

    执行结果:



    欧耶,-1 >=2 就这样出现了……


    我一開始认为计算机是不是脑残了,会有这样的结果? 


    我怀疑是 vector.size 的返回值有问题,查文档,发现原来返回类型是 size_type  也就是 unsigend int, 这下子。知道是怎么一回事了。

    这样測试,结果就明了了,再上代码:

    #include <iostream>
    #include <vector>
    
    using namespace std;
    
    
    int main()
    {
    	vector<string> vctStr;
    	vctStr.push_back("Hello");
    	vctStr.push_back("World");
    
    	cout<<"VctSize: "<<vctStr.size()<<endl;    // VctSize: 2
    
    	int iType = -1;
    
    	if (iType >= vctStr.size() )
    	{
    		cout<<"Amazing ……"<<endl;			// -1 竟然大于2 ?!
    		cout<<"iType: "<<iType<<", size: "<<vctStr.size()<<endl;
    		cout<<"Here!: iType:"<<(unsigned int)(iType)<<endl;		// 新加一行信息打印, 看到这里就懂了。
    		
    	}
    	
    	return 0;
    }

    上图:



    计算机并没有脑残,仅仅是在比較的时候,默认做了类型转换,将负数进行了转换

    即 if (iType >= vctStr.size() ) 实际上应该是   if ( (unsigned int)iType >= vctStr.size() )。 这种话,肯定是大于2的了。


    为此我还专门上网查找了关于 负数在计算机中的存储问题。看完之后,明确了怎样求一个常见数据类型的最大值问题

    再上代码:

    #include <iostream>
    #include <vector>
    
    using namespace std;
    
    
    int main()
    {
    	int i = -1;
    	cout<<"unsigned int max: "<< (unsigned int)(i) <<endl;
    	cout<<"         int max: "<< (unsigned int)(i)/2<<endl;
    	
    	return 0;
    }

    图:




  • 相关阅读:
    BZOJ-1497 最大获利
    POJ-3680 Intervals & NOI 2008 志愿者招募 费用流
    CodeForces 663E Binary Table
    南昌区域赛-G Eating Plan
    HDU-5909 Tree Cutting
    BZOJ-4589 Hard Nim
    UVA-12633 Super Rooks on Chessboard
    SPOJ-TSUM Triple Sums
    HDU-4609 3-idiots
    Kattis-aplusb A+B problem
  • 原文地址:https://www.cnblogs.com/yfceshi/p/7261610.html
Copyright © 2011-2022 走看看