2011-12-30 61 views
9

我是編程的新手,對C#感興趣。我正在學習數組,並且必須將我的變量(checkNum)與我的數組(myNums [10])進行比較。我閱讀這裏和其他幾個網站的帖子,看到了如何比較,但如何正確顯示比較結果,如下面的if/else語句所示:(我會繼續研究,但會欣賞和輕輕推敲。正確的方向不一定是因爲我想了解答案):)將int值與數組進行比較,然後在值匹配或不匹配時顯示

這裏是我的代碼:

int[] myNums = new int[10]; 
int checkNum; 
Console.WriteLine("Enter 10 numbers:"); 

for (int i = 0; i < 10; i++) 
{ 
    Console.Write("Number {0}: ", i + 1); 
    myNums[i] = int.Parse(Console.ReadLine()); 
} 
Console.WriteLine("You entered:"); 
foreach (int x in myNums) 
{ 
    Console.Write("{0} ", x); 
} 
Console.ReadLine(); 

Console.WriteLine("Enter another number:"); 
checkNum = int.Parse(Console.ReadLine()); 
bool exists = myNums.Contains(checkNum); 

if (checkNum == myNums[10]) 
{ 
    Console.WriteLine("Your number {0} is in the Array.", checkNum); 
} 
else 
{ 
    Console.WriteLine(
     "Your number {0} does not match any number in the Array.", 
     checkNum); 
} 
Console.ReadLine(); 
+1

除了所有答案在數組邊界和不使用存在var我會補充說,它通常是一個好主意,使用int.TryParse(字符串,out int),以避免不良輸入。 – Nickolodeon 2011-12-30 21:51:01

+1

+1尋求幫助而不是要求回答 – 2011-12-30 21:55:44

回答

0

您需要通過數組進行迭代,看看是否值是它:

bool exists = false; 
for (int i=0; i<myNums.Length; i++) 
{ 
    if (checkNum == myNums[i]) 
    { 
     exists = true; 
     break; 
    } 
} 

if (exists) 
{ 
    Console.WriteLine("Your number {0} is in the Array.", checkNum); 
} 
else 
{ 
    Console.WriteLine(
     "Your number {0} does not match any number in the Array.", 
     checkNum); 
} 
+0

'Contains()'使用起來更加簡單。 – 2011-12-30 21:41:52

+0

包含更簡單,但是您可以執行更大的迭代結果,因此您可以看到哪個索引是平等的,哪個不是。 – 2011-12-30 21:48:37

+0

那麼你會使用'IndexOf'並檢查'-1',仍然不需要在你的代碼中循環。無論如何,OP不需要知道索引。 – 2011-12-30 21:58:56

6
bool exists = myNums.Contains(checkNum); 
if(checkNum == myNums[10]) 
{ 
    Console.WriteLine("Your number {0} is in the Array.", checkNum); 
} 
else 
{ 
    Console.WriteLine("Your number {0} does not match any number in the Array.", checkNum); 
} 

bool exists = myNums.Contains(checkNum); 
// or simply if(myNums.Contains(checkNum)) as you don't use the variable again 
if(exists) 
{ 
    Console.WriteLine("Your number {0} is in the Array.", checkNum); 
} 
else 
{ 
    Console.WriteLine("Your number {0} does not match any number in the Array.", checkNum); 
} 

您正確地執行了檢查,但你不使用的結果(exists)和簡單(嘗試)新號碼比較數組中的最後一個元素。當然,在這一點上你的程序只會崩潰,因爲你已經超出了你的數組的範圍。

數組爲0索引,即nums[10]包含索引0-9。

+0

'Contains'會讓我的一堆代碼簡單得多。 :) ++ – John 2011-12-30 21:46:09

+0

謝謝。我看到我現在使用「if」語句的其他變量對執行比較的bool「exists」進行了錯誤判斷。謝謝。 – Darwin 2011-12-30 21:51:21

0

爲什麼你有最後一條if語句檢查:checkNum == myNums[10]?它應該使用exists變量。