2013-10-07 35 views
0

我正在做一个作业问题,我需要编写一个输入五个数字的应用程序,每个数字都在10到100之间(包括10和100)。当每个数字被读取时,只有当它不是已经读取的数字的副本时才显示它。提供最糟糕的情况,其中所有五个数字都不相同。为了解决这个问题,尽可能使用最小的数组,并在用户输入每个新值后显示一组完整的唯一值。使用数组显示一组唯一的值

我到目前为止工作正常。只有当程序运行时,如果所有五个数字都是唯一的,我会一直收到未处理的错误。它告诉我索引超出了数组的范围。只有我不确定它为什么这样做,而我在for循环中看不到任何错误。

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

namespace Ten_Seven_Thirteen 
{ 
class Program 
{ 
    static void Main(string[] args) 
    { 
     const int SIZE = 5; 
     int[] nums = new int[SIZE]; 
     int a; 
     int b; 
     int c = 0; //c is the amount of numbers currently entered 
     int number; 
     Console.WriteLine("Input five numbers between 10 and 100 (inclusive): \n"); 

     for (int count = 0; count < SIZE; count++) 
     { 

      number = Convert.ToInt32(Console.ReadLine()); 
      if (number >= 10 && number <= 100) //Verify whether or not the number meets the criteria 
      { 
       for (a = 0; a < c; a++) 
       { 

        // The following if condition checks for duplicate entrees. 
        if (number == nums[a]) 
        { 
         Console.WriteLine("Duplicate number.\n"); 
         break; //Breaking the loop prevents the duplicate number from entering the array 
        } 

       } // end for 

       // if number is not a duplicate, enter it in array 
       if (number != nums[a]) 
       { 
        nums[c++] = number; 
       } // end if - not duplicate 

       Console.WriteLine("The non-duplicate values are:\n"); 

       //display array of unique numbers 
       for (b = 0; nums[b] != 0 && b < SIZE; b++) 
       { 
        Console.WriteLine(nums[b]); 

       } // end for loop and display array 
      } // end if - validate and test 
      else 
       Console.WriteLine("invalid number."); 
      Console.WriteLine("\n"); 

     } // end for - get 5 numbers 



     } 
    } 
}// end Ten_Seven_Thirteen 

回答

4

这是因为这个代码..

for (b = 0; nums[b] != 0 && b < SIZE; b++) 
{ 
    Console.WriteLine(nums[b]); 
} 

您不能检查NUMS [B]有。你需要找出一个更好的方法来切断它(我会把它留给你,因为它是功课,或者你可以在评论中提问)。 b将进入SIZE,然后它会检查数量[SIZE],最后一个索引的数量是SIZE - 1,因此你会得到一个索引超出范围例外。

此外,此代码将无法正常工作,因为它只提示你5次,不管它们是否独一无二。尝试不同的类型的循环。

另外...这是稍微偏离主题,但因为你正在学习:命名你的变量有意义。 a,b,c使它变得神秘而难以阅读。睡觉后你不会知道你在做什么。更好的命名意味着你需要更少的评论,因为代码证明自己。专业代码中没有太多评论,尽管高中教师会告诉你。