2013-10-26 20 views
1

我基本上想檢查newValue是否超過targetValue。但是targetValue可能是正數或負數,所以如果(newValue < targetValue)不一定有效。這個正面/負面的支票可以簡化嗎?

我編寫它下面的方式,我可以在這裏得太多的東西,但我不知道是否有改寫的方式,如果檢查多一點優雅......

var newValue = 0; 

function ChangeValue (targetValue : int) 
{ 
    var isTargetPositive = (targetValue > 0); 

    if (isTargetPositive && newValue < targetValue || !isTargetPositive && newValue > targetValue) 
     newValue = math.moveTowards(newValue, targetValue, 1); 
    else 
     // Do something else 
} 
+1

任何你初始化「NEWVALUE」零,所以如果「targetValue」大於零,「NEWVALUE」將* *總是**小於「targetValue」。 – Pointy

+0

'newValue Blender

+1

該代碼無法正常工作。 –

回答

2

我能想到的唯一的事情,讓您的條件,正是因爲他們是被移除isTargetPositive變量,if語句具有以下替換您:

if (targetValue > 0 ? newValue < targetValue : newValue > targetValue) 
+0

謝謝。這有點簡單。 – Essential

-1

測試(輸入:5) isTargetPositive - 匹配 NEWVALUE < targetValue - 匹配

測試(輸入:-1)! isTargetPositive - 匹配 NEWVALUE> targetValue - 匹配

霧化+ ve或-ve整數,它將匹配的IF。

isTargetPositive & & newValue < targetValue,same right?爲什麼使用& &? 我認爲一個條件就足夠了。

1
var newValue = 0; 
    function ChangeValue (targetValue) 
    { 
     if ( 
    ((targetValue > 0) && (newValue < targetValue)) 
    || 
    ((targetValue < 0) && (newValue > targetValue)) 
      ) 
     { 
      newValue = math.moveTowards(newValue, targetValue, 1); 
     }  
     else{ 
      // Do something else 
     } 
    } 
+1

這並沒有真正簡化它... – Tyler

+0

有點凌亂,對吧? :d –

1

你總是可以做一個子功能,如果這還不夠

function abs_compare(target, number) { 
    return target != 0 && ((target > 0 && target > number) || target < number); 
} 

if (abs_higher(targetValue, newValue)) { 
    newValue = math.moveTowards(newValue, targetValue, 1); 
} 

清楚,我也寧願target != 0而不是雙重檢查它是否優於或劣於0,因爲它是在更明確的條件聲明它是一個禁止值。另外,Pointy說,既然你已經初始化newValue爲0,它將始終保持爲0,因爲ChangeValue是一個函數,所以它現在是false。在函數調用之前可以更改newValue。

UPDATE

我可能讀得太快。將目標比較爲0將不會保持您的實際邏輯,並且與重複檢查相同。無論如何,你仍然可以使用一個功能。

也是最好的答案寧願使用條件target > 0 ? target > number : target < number

2

這幾乎是相同的情況下,在我的chess project,我改變了:

if((obj.ActiveColor&&current_val>0) || (!obj.ActiveColor&&current_val<0)){} 

var impossible_to_name = (current_val * (obj.ActiveColor?1:-1)); 

if(impossible_to_name>0){} 

我知道你不需要緩存var,但在我的情況下,我將在稍後使用它,所以我緩存了它,我的代碼非常複雜,我甚至不能提供一個pr oper name to my var,我也不完全確定這是否會對你有幫助,如果我不能將它翻譯成你的代碼,你可能無法做到,但我會嘗試再次理解我的代碼並進行編輯我的答案。

注:我的代碼被包裹在if(current_val){...}所以價值除了0