我的代码如下,我是要在30行比较两个式子计算的结果,但是比较出来的结果是错误的,应该前半部分计算得出的是-2,后半部分是9,比较结果应该是错误的,不会进入这个if{}语句,但是仍然进入了。
1 #include<iostream> 2 #include<vector> 3 using namespace std; 4 class Solution { 5 public: 6 bool IsContinuous( vector<int> numbers ) { 7 int luckyCount = 0; 8 vector<int> tag; 9 //tag.reserve(numbers.size()); 10 int minNumber = 1<<30; 11 int maxNumber = 0; 12 for (int i = 0; i < numbers.size(); i++) 13 { 14 if (numbers[i] == 0) 15 { 16 luckyCount++; 17 } else if (numbers[i] < minNumber) { 18 minNumber = numbers[i]; 19 } else if (numbers[i] > maxNumber) { 20 maxNumber = numbers[i]; 21 } 22 tag.push_back(0); 23 } 24 25 cout<<maxNumber - minNumber + 1<<endl; 26 cout<<tag.size() + luckyCount<<endl; 27 int temp1 = maxNumber - minNumber + 1; 28 int temp2 = tag.size() + luckyCount; 29 cout<<(temp1 > temp2)<<endl; 30 if ((maxNumber - minNumber + 1) > (tag.size() + luckyCount)) 31 { 32 cout<<"(maxNumber - minNumber + 1) > (tag.size() + luckyCount)"<< 33 ((maxNumber - minNumber + 1) > (tag.size() + luckyCount))<<endl; 34 return false; 35 } 36 37 for (int i = 0; i < numbers.size(); i++) 38 { 39 if (!(numbers[i] == 0)) 40 { 41 //numbers[i]可能是一个很大的数,超过了tag的size 42 tag[numbers[i] - minNumber] = 1; 43 } 44 } 45 for (int i = 0; i < tag.size();i++) 46 { 47 if (tag[i] == 0) 48 { 49 luckyCount--; 50 } 51 if (luckyCount < 0) 52 { 53 return false; 54 } 55 } 56 return true; 57 } 58 }; 59 int main() 60 { 61 int array[] = {3,0,0,0,0}; 62 vector<int> vec(array, array + sizeof(array)/sizeof(int)); 63 cout<<Solution().IsContinuous(vec); 64 return 0; 65 }
30行里面tag.size()返回一个unsigned int,因此(tag.size() + luckyCount)为unsigned int,而(maxNumber - minNumber + 1)是负数,是signed int,unsigned类型和signed类型比较的时候会出现奇怪的问题。参考http://bbs.csdn.net/topics/391870819?page=1
30行改成if ((maxNumber - minNumber + 1) > (int)(tag.size() + luckyCount))就不会进去了
谢谢,懂了
你跑起来测试了嘛?(maxNumber - minNumber + 1) 这个结果是-2 ??
tag.size() + luckyCount 这个值是9 ??
是9,另一位小哥解决了。是因为tag.size()返回的是无符号类型的原因