簡體   English   中英

在 return 語句中嵌套條件運算符

[英]Nesting conditional operators in a return statement

因此,我設置了一個代碼,用於查找用戶輸入與 51 之間差異的幅度(絕對值)。如果用戶輸入大於 51,則結果將增加三倍。 不復雜。 為了盡量減少代碼本身,我想出了這個。

// Compare and determine the correct output based on program's 
// paramters:
//
// - find absolute value of input - 51
// - if input > 51 then multiply result by 3
//-----------------------------------------------------------

int calcDiff(int x) {
      const int base = 51;
      int result     = x - base;    
      return x > base ? 3*result : (result < 0 ? ~result + 1 : result);
 }

所以問題是:

這合適嗎? 我知道它有效,但我更好奇這是否是不好的做法,以及有一天會如何嚴重咬我。 這只是意見還是不喜歡使用scanfgets 有打死馬的表情包嗎? 因為我想用它。

  1. return語句中嵌套條件本身並沒有錯。

  2. ~result + 1不好。 您正在嘗試否定result 正確的方法是簡單的-result ~result + 1依賴於無所不在的二進制補碼表示,但這種表達更奇怪且沒有必要。

  3. 你不需要(result < 0 ? ~result + 1 : result) 僅當x > base為假時才計算此表達式,在這種情況下result必須小於或等於零,並且您想要返回-result ,因為它處理小於零的情況(返回-result )和等於為零的情況(返回0 ,當result為零時與-result相同)。

所以return語句可以寫成:

return x > base ? 3*result : -result;

或者:

return result > 0 ? 3*result : -result;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM