2016-10-07 3 views
0

이번 학기 C# 수업을 듣고 있으며 지금까지 꽤 재미있었습니다. 배열에서 숫자를 추가하고, 배열에 입력 된 숫자를 확인하고, 배열에서 숫자를 찾고, 배열에서 숫자를 정렬하고, 배열 숫자를 기반으로 통계를 생성하는 과제가 있습니다. 마지막으로 응용 프로그램을 종료하십시오.배열에 숫자 추가 C# 유효 숫자 만 사용

지금까지 나는 입력 된 데이터가 숫자라는 것을 확인하면서 배열에 숫자를 추가하는 데 약간의 문제가있었습니다. 나는 그것을 이해하려고하고 있다고 생각하지만 도움은 언제나 감사합니다. 그리고, 내 findData() 메소드는 괜찮아 보입니까?

다시 한 번이 질문을 읽어 주셔서 감사합니다.

class Program 
{ 

    static char myChoice = Console.ReadKey().KeyChar; 
    static double[] myArray = new double[100]; 
    static void Main(string[] args) 
    { 



     while (true) 
     { 

      Console.WriteLine("Welcome to Lab 2"); 
      Console.WriteLine(); 
      Console.WriteLine("Main Menu"); 
      Console.WriteLine("1- Add new data"); 
      Console.WriteLine("2- See all data"); 
      Console.WriteLine("3- Find a number"); 
      Console.WriteLine("4- Sort the data"); 
      Console.WriteLine("5- Create statistics"); 
      Console.WriteLine("6- Exit Program"); 


      switch (myChoice) 
      { 
       case '1': 
        Console.WriteLine("1- Add new data"); 
        addData(); 
        break; 

       case '2': 
        Console.WriteLine("2- See all data"); 
        seeData(); 
        break; 

       case '3': 
        Console.WriteLine("3- Find a number"); 
        findData(); 
        break; 

       case '4': 
        Console.WriteLine("4- Sort the data"); 
        sortData(); 
        break; 

       case '5': 
        Console.WriteLine("5- Create statistics"); 
        createData(); 
        break; 

       case '6': 
        Console.WriteLine(); 
        exitProgram(); 
        break; 

      } 
     } 
    } 

    //This method will add numbers to the array 
    public static void addData() 
    { 
     bool isNumber = false; 
     double number; 
     double temp; 

     for (int i = 0; i < myArray.Length; i++) 
     { 
      Console.WriteLine("Enter a number you would like to add"); 

      myArray[i] = Convert.ToDouble(Console.ReadLine()); 
      temp = myArray[i]; 

      if (!Double.TryParse(temp, out number)) 
      { 
       Console.WriteLine("Invalid input. Please enter a valid number") 
      } 

      else 
      { 

      } 
     } 
    } 

    //This method will see the numbers entered in the array 
    public static void seeData() 
    { 
     foreach (var item in myArray) 
     { 
      Console.WriteLine(item.ToString()); 
     } 
    } 

    //This method will find a specific number within the array and check if it has already been entered 
    public static void findData() 
    { 

     Console.WriteLine("Find a number"); 
     string myChoice = Console.ReadLine(); 
     double number; 
     bool isNumber = Double.TryParse(myChoice, out number); 

     { 

     } 

    } 

    //This method will sort the array ascending to descending 
    public static void sortData() 
    { 
     Console.WriteLine("The array has been sorted in ascending order"); 
     Array.Sort(myArray); 
     Console.WriteLine("The array has been sorted in descending order"); 
     Array.Reverse(myArray); 
    } 

    //This method will create statistics based on the numbers in the array 
    public static void createData() 
    { 

     //Sum 
     double sum = myArray.Sum(); 
     Console.WriteLine("The total sum of the array is: " + sum); 

     //Average 
     double average = sum/myArray.Length; 
     Console.WriteLine("The average number of the array is: " + average); 

     //Maximum 
     double maximum = myArray.Max(); 
     Console.WriteLine("The maximum value in the array is: " + maximum); 

     //Minimum 
     double minimum = myArray.Min(); 
     Console.WriteLine("The minimum value in the array is: " + minimum); 

     //Mean 
     double mean = sum/myArray.Length; 
     Console.WriteLine("The mean average of the array is: " + mean); 
    } 

    //This method will exit the program 
    public static void exitProgram() 
    { 
     Environment.Exit(0); 
    } 
} 

}

+0

정확한 문제는 무엇입니까? – A3006

+0

[평균 및 산술 평균은 정확히 동일합니다] (http://stats.stackexchange.com/questions/14089/what-is-the-difference-between-meanvalue-and-average) 허용되는 경우 Enumerable.Min, Sum 및 Max를 사용하려면 Enumerable.Average를 사용할 수도 있습니다. 또한 원하는 배열 크기를 입력하도록 사용자에게 제공하는 것이 더 유연 할 수 있습니다. – Martheen

답변

1

내 findData() 메소드가 좋아 보입니까?

findData() 메서드는 아무 것도 없습니다.

여기에 귀하의 addData 방법이 훨씬 이해가되지 않습니다

public static void addData() 
      { 
       for (int i = 0; i < myArray.Length; i++) 
       { 
        bool success = false; 
        while (!success) 
        { 
         Console.WriteLine("Enter a number you would like to add"); 
         string input = Console.ReadLine(); 
         double number; 
         if (Double.TryParse(input, out number)) 
         { 
          success = true; 
          myArray[i] = number; 
         } 

         else 
         { 
          Console.WriteLine("Invalid input. Please enter a valid number") 
         } 
        } 
       } 
      } 
0

하나의 방법이다 : 먼저 배열로 두 배 값을 삽입 한 다음 확인 이 값이 double이면 배열이 double 유형이고 해당 유형의 값만 포함 할 수 있기 때문에 확실합니다.

또한 사용자 입력이 유효하지 않은 경우 Convert.ToDouble이 예외를 throw 할 수 있습니다. 하지만 당신은 Double.TryParse 메서드를 사용하는 지점을 참조하십시오. 문자열 (첫 번째 매개 변수)이 유효한 숫자 인 경우 true를 반환합니다.

//This method will add numbers to the array 
public static void addData() 
{ 
    double number; 

    for (int i = 0; i < myArray.Length; i++) 
    { 
     Console.WriteLine("Enter a number you would like to add"); 
     // read user input 
     string input = Console.ReadLine(); 
     // condition is true if user input is a number 
     if (double.TryParse(input, out number)) 
      myArray[i] = number; 
     else 
      Console.WriteLine("Invalid input. Please enter a valid number"); 
    } 
} 

당신이 LINQ를 사용하여 배열에 숫자를 찾으려면 exacly 그 않는 확장 메서드를 포함합니다 : 그래서는, addData 방법은 다음과 같이 보일 것이다 배열 요소가있는 경우는 true를 반환하고, 그렇지 않은 경우는 false :

//This method will find a specific number within the array and check if it has already been entered 
public static void findData() 
{ 
    double number; 
    Console.WriteLine("Find a number"); 
    string input = Console.ReadLine(); 
    // we use the same logic here as in the addData method to make sure the user input is a number 
    if (!double.TryParse(input, out number)) 
    { 
     bool found = myArray.Contains(number); 
     if (found) 
      Console.WriteLine("Array has number {0}", number); 
     else 
      Console.WriteLine("Array doesn't have number {0}", number); 
    } 
    else 
    { 
     Console.WriteLine("Invalid input. Please enter a valid number"); 
    } 
} 
0

이것은 당신의 추가 문제를 해결해야

public static void findData() 
{ 
    Console.WriteLine("Find a number"); 
    string myChoice = Console.ReadLine(); 
    double number = -1; 

    if(!Double.TryParse(myChoice, out number)) 
    { 
     Console.WriteLine("Invalid number"); 
    } 
    else if (Array.IndexOf<double>(myArray, number) == -1) 
    { 
     Console.WriteLine("Number does not exist"); 
    } 
    else 
    { 
     Console.WriteLine("Number does exist"); 
    } 
} 
+2

입력이 유효하지 않은 경우 for 루프는 여전히 계속됩니다. –

+0

@CodeJoy 예,이 경우 배열 요소에는 double에 대한 기본값 인 0.0d가 포함되어 있으므로 프로그램 실행을 손상시키지 않습니다. 또한 질문은 그 상황에서 메소드의 동작을 지정하지 않으므로 코드는 완벽하게 유효합니다. 다른 경우에는 부울 플래그가있는 내부 do-while 루프를 사용하여 사용자 입력이 유효한지 여부를 나타낼 수 있습니다. – Alex

+0

@Alex 입력이 유효하지 않은 경우 왜 - i가 아닌가? – Martheen