2016-02-18 22 views
-3
{ 
     Random r = new Random(); 
     int current = 0; 
     int noa = 0; 
     while (current != 6) { 
      current =r.Next(1,7); 
       noa += 1; 
       Console.WriteLine(current + " has been rolled."); 
     } 

     if (noa >= 10) 
     { 
      Console.WriteLine("You were unlucky and it took you "+ noa + " times to roll a 6!"); 
     } 
     if (noa <= 5) 
     { 
      Console.WriteLine("You were quite lucky and it took you " + noa + " times to roll a 6!"); 
     } 
     else 
     { 
      Console.WriteLine("It took you " + noa + " times to roll a 6!"); 
     } 

     Console.ReadKey(); 


    } 
} 

} 工作時NOA(嘗試次數)高於10和它顯示的是這樣出現的問題:C#否則並不如預期

2已經鋪開。
5已滾動。
4已滾動。
5已滾動。
5已滾動。
1已滾動。
2已滾動。
1已滾動。
3已滾動。
4已滾動。
6已滾動。
你倒黴了,它花了11次滾6!
它花了11次滾6!

而我不想發生的是控制檯寫第二行「花了11次滾6!」。 這是怎麼回事?先謝謝你。

回答

7

你必須讓它elseif

if (noa >= 10) 
{ 
    Console.WriteLine("You were unlucky and it took you "+ noa + " times to roll a 6!"); 
} 
else if (noa <= 5) 
{ 
    Console.WriteLine("You were quite lucky and it took you " + noa + " times to roll a 6!"); 
} 
else 
{ 
    Console.WriteLine("It took you " + noa + " times to roll a 6!"); 
} 

編輯 同意@Kalmino,問題的原因是所有的條件一起處理在一個條件與if... elseif... else分支。

+2

@tagito你有它的方式(與此相反)是將> = 10和下一個if/else視爲兩個單獨的語句。否則,如果該CarbineCoder放入它們全部3個,因此它們將它們評估在一起而不是檢查> = 10,然後檢查<= 5或其他。 –

+0

謝謝,現在我明白了,但如果我需要4個ifs呢?我是否可以通過「if; else if; else if; else;」來做到這一點?? – tagito

+1

你只需要在最後一個else語句前添加一個else else就可以了 – CarbineCoder

3

因爲這

if (noa <= 5) 
{ 
    Console.WriteLine("You were quite lucky and it took you " + noa + " times to roll a 6!"); 
} 
else 
{ 
    Console.WriteLine("It took you " + noa + " times to roll a 6!"); 
} 

如果noa>5會發生什麼呢?