# C++ ,两个计算结果比较大小的问题

0

``` 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 }```

1

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))就不会进去了

hehe_54321 | 小虾三级 |园豆：750 | 2017-12-09 15:36

AdamDuncan | 园豆：182 (初学一级) | 2017-12-12 21:18

0

tag.size() + luckyCount     这个值是9 ？？

warmpan | 园豆：214 (菜鸟二级) | 2017-12-09 15:01

您需要登录以后才能回答，未注册用户请先注册