2012-02-15 17 views
0

比較多個值,我有這樣的代碼:一次使用&&

if ((total == (total1 && total2 && total3))) 
    { 
     [scrollview.contentOffset = CGPointMake (0,0)]; 
    } 

這裏就是它的類似按鈕的動作:

if (sender.tag == 1) 
    { 
     total1 = 10; 
    } 

if (sender.tag == 2) 
    { 
     total2 = 20; 
    } 

if (sender.tag == 3) 
    { 
     total3 = 30; 
    } 

我想回去的起始頁滾動視圖,如果用戶點擊三個正確的按鈕(類似於密碼鍵)。

邏輯運算符&&在Objective-C中是否正常運行,並且我是否正確使用它?

+1

您需要說明total,total1,total2和total3可能具有的值。 – 2012-02-15 01:07:42

+0

你去了。希望它有助於找到我的問題的答案。 – SeongHo 2012-02-15 01:20:25

+1

你有多少個按鈕?當用戶按下這些按鈕時會發生什麼,但是其他按鈕呢?當用戶按下其中一個按鈕兩次或更多次時會發生什麼? – sch 2012-02-15 01:44:35

回答

3
if ((total == (total1 && total2 && total3))) 

你不能那樣做。你必須分別明確地比較每一個。

if ((total == total1) && (total == total2) && (total == total3))) 

但還有如何total可以等於所有三個同時,雖然這個問題。

+0

我試過了,但是當我開始運行應用程序時它會執行代碼。 – SeongHo 2012-02-15 01:14:51

0

什麼你當前的代碼基本上說的是:「如果total是‘真’和total1total2total3也都非零或者total是零和total1total2total3也都爲零,然後做一些事情」。

您在那裏的&&正在做邏輯/布爾比較。它將其論點視爲truefalse,並且如果在任何其他情況下兩個參數評估爲truefalse,則返回true==total的值與從&&表達式獲得的值truefalse進行比較。這可能不是你想要的。

好像可能要被說是什麼「如果total等於total1total2的總和,total3,然後做一些事情。」假如是這樣的話,你會怎麼做:

if (total == (total1 + total2 + total3)) { 
    [scrollview.contentOffset = CGPointMake (0,0)]; 
} 
+0

我試過了,但是當我開始運行應用程序時它會執行代碼。 – SeongHo 2012-02-15 01:15:08

1

在您的代碼:

if ((total == (total1 && total2 && total3))) 
{ 
    [scrollview.contentOffset = CGPointMake (0,0)]; 
} 

當if表達式,(total1 && total2 && total3)首先評估。這可以是YESNO(如果您願意,也可以是true或false)或(0或1)。

所以你的代碼等同於以下內容:

BOOL allVariablesAreNotZero = total1 && total2 && total3; 
if (total == allVariablesAreNotZero) 
{ 
    [scrollview.contentOffset = CGPointMake (0,0)]; 
} 

編輯問題被更好地解釋

後讓你的按鈕執行以下操作按下時:

- (void)buttonClicked:(id)sender 
{ 
    UIButton *button = (UIButton *)sender; 
    buttonsCombination = buttonsCombination | (1 << button.tag); 
} 

其中buttonsCombination是一個NSUInteger。然後使用下面的測試,看看是否被按下的按鈕是正確的人(我有三個按鈕這樣做,但你猜的想法)

NSUInteger correctCombination = (1 << button1) | (1 << button2) | (1 << button3) 
if (buttonsCombination == correctCombination) { 
// The combination is correct 
} else { 
    // The combination is incorrect 
} 
buttonsCombination = 0; 

最後,請注意這個作品,因爲有足夠的位在一個NSUInteger中爲30個按鈕。這裏我用bitwise operators|<<

+0

我可以問一個愚蠢的問題嗎? button1,button2和button3是什麼?對不起,我是一個初學者。 – SeongHo 2012-02-15 02:49:56

+0

形成正確組合的按鈕標籤。 – sch 2012-02-15 02:52:03

0

試圖確定您在其他兩個答案的意思是你的意見是什麼「我嘗試過,但它執行的代碼,當我開始運行應用程序」也許這是你想達到什麼目的:

/* all in your button handler */ 
switch(sender.tag) 
{ 
    case 1: 
     total1 = 10; 
     break; 
    case 2: 
     total2 = 20; 
     break; 
    case 3: 
     total3 = 30; 
     break; 
    default: 
     break; // other buttons are ignored 
} 
// check it latest click means the total is now correct 
if((total1 + total2 + total3) == total) 
{ 
    [scrollview.contentOffset = CGPointMake (0,0)]; 
} 

因此,你更新任何totalX的按鈕點擊,然後檢查條件重置滾動。

+0

它也沒有工作。 – SeongHo 2012-02-15 02:13:31