有符号数、无符号树混合计算问题。
今天在線刷題,其中一個問題總是結(jié)果跟期望的不一樣,在一次次的檢查程序邏輯、確認無誤后,還是不能通過,不得已用VS開始調(diào)試!
這里是我的程序代碼:
1 // maxDepth.cpp : 定義控制臺應用程序的入口點。 2 // 3 4 #include "stdafx.h" 5 #include<vector> 6 #include<iostream> 7 #include<limits.h> 8 9 using namespace std; 10 11 class TreeNode { 12 public: 13 int val; 14 TreeNode *left, *right; 15 TreeNode(int val) { 16 this->val = val; 17 this->left = this->right = NULL; 18 } 19 }; 20 21 class Solution { 22 public: 23 /** 24 * @param root: The root of binary tree. 25 * @return: An integer 26 */ 27 void PreOrder(TreeNode *root, std::vector<TreeNode*> &path) 28 { 29 if (!root) 30 return; 31 path.push_back(root); 32 if(!root->left && !root->right) 33 if (path.size() > max) 34 max = path.size(); 35 if(root->left) PreOrder(root->left, path); 36 if(root->right) PreOrder(root->right, path); 37 path.pop_back(); 38 } 39 int maxDepth(TreeNode *root) { 40 // write your code here 41 if (!root) 42 return 0; 43 std::vector<TreeNode*> path; 44 PreOrder(root, path); 45 return max; 46 } 47 Solution():max(INT_MIN){;} 48 private: 49 int max; 50 }; 51 52 void Test() 53 { 54 int c = -1; 55 if (c > (unsigned)1)std::cout << "c > -1" << std::endl; 56 c = INT_MIN; 57 //std::cout << c; 58 //std::cout << 59 60 std::cout << -7 + (unsigned)5 << std::endl; 61 std::cout << -7 + (unsigned)10 << std::endl; 62 63 //bool b = c > 1; 64 //std::cout << b ; 65 66 } 67 68 int _tmain(int argc, _TCHAR* argv[]) 69 { 70 TreeNode *root = new TreeNode(0); 71 Solution so; 72 std::cout << so.maxDepth(root) << std::endl; 73 74 Test(); 75 76 77 78 return 0; 79 }調(diào)試時發(fā)現(xiàn),33行處if (path.size() > max)怎么都不會執(zhí)行。如此就明白了,這里涉及到有符號、無符號數(shù)的混合運算問題!
1. int max定義的是有符號數(shù),并且初始化為最小的負數(shù)INT_MIN,而size()函數(shù)返回的是無符號數(shù),在混合運算中,會把有符號數(shù)轉(zhuǎn)化為無符號數(shù)。負數(shù)的第一位為1,轉(zhuǎn)化為無符號數(shù)之后大于所有的正數(shù),所以這里怎么都不會執(zhí)行!
2. 轉(zhuǎn)化過程后運算時,可能會發(fā)生溢出,C的簡單做法就是截斷!如我這里的test()函數(shù)的編譯信息。
3. 實際上,我在編譯時,VS已經(jīng)對33行發(fā)出警告“?warning C4018: “>”: 有符號/無符號不匹配”,可是我卻忽視了這個做法。所以,絕不要忽視編譯器的任何警告。
4.實際上,在CSAPP第二章中,就對有符號、無符號數(shù)進行了深入的討論。并且得出了“無符號數(shù)的帶來的弊端遠大于它所帶來的作用,盡量少使用無符號數(shù)”的結(jié)論。可是C++標準庫中,很多關于size(),capacity()函數(shù)返回的都是無符號數(shù),所以處理這樣的程序中,必須小心處理有符號無符號數(shù)混合運算的問題!
?
?
轉(zhuǎn)載于:https://www.cnblogs.com/bitpeng/p/4783984.html
總結(jié)
以上是生活随笔為你收集整理的有符号数、无符号树混合计算问题。的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 新手WEB开发者易出现的30个问题(转)
- 下一篇: 爬虫二(urllib模块)