2012-05-04 2 views
3

Мне необходимо написать программу, которая считывает данные в массив типа int. Допустимые значения от 0 до 10. ваша программа должна определить, сколько значений было введено. Выводит список различных записей и подсчет того, сколько раз, что вступление произошлоРассчитать частотное распределение массива?

У меня возникли проблемы с Bolded стороны, это то, что я до сих пор ...

static void Main(string[] args) 
{ 
    Console.WriteLine("How many scores will you enter?"); 

    int total = 0; 
    string inValue; 
    string Size = Console.ReadLine(); 
    int arraySize = Convert.ToInt32(Size); 
    int [] ScoreArray = new int [arraySize]; 

    for (int i = 0; i < ScoreArray.Length; i++) 
    { 

     Console.Write("Enter a Number between 0 and 10, #{0}: ", i + 1); 
     inValue = Console.ReadLine(); 
     ScoreArray[i] = Convert.ToInt32(inValue); 

     total += ScoreArray[i]; 
    } 

    Console.WriteLine("Number of scores entered: " + arraySize); 
    Console.Read(); 
} 
+0

магазин запись в карту с ключом является отчетливым значением и значение того, сколько раз вы столкнулись с этим ключом. –

+1

Что вы пробовали? В любом случае, рассмотрите это: 'ScoreArray [theNumber] + = 1' вместо' ScoreArray [i] = ... '; какая разница? –

+0

@pst, что вы понимаете от 'это то, что я до сих пор ' –

ответ

0

Я думаю, что ключ здесь допустимых значений находятся в диапазоне 0-10. Я хотел бы использовать индекс массива для хранения каждого самого значения. Например, если вы обрабатываете значение 5, приращение values[5].

Так первый вы Изя массив как:

int[] values = new int[11]; //Values 0-10 

Затем цикл, пока пользователь просто вводит пустого:

while(true) 
{ 
    string inValue = Console.ReadLine(); 
    if(String.IsNullOrEmpty(inValue)) break; 

    values[Convert.ToInt32(inValue)]++; //Bounds checking would be nice here 
} 

Вы можете отобразить отсортированный отчетливый список, обернув через массив один раз и печать любой индекса с величиной больше 0:

for(int i = 0; i < values.length; i++) 
{ 
    if(values[i] > 0) 
    { 
     Console.WriteLine("Value {0} was entered {1} time(s)..", i, values[i]); 
    } 
} 

Это, скорее всего, то, что ваш профессор ищет. Я не проверял код выше, это ваша работа :)

0

Этот код делает все, что вам нужно:

 static void Main(string[] args) 
     { 
      //input data 
      int[] inputArray = new int[5]; 
      int enteredCount = 0; 
      string enteredLine = string.Empty; 

      Console.WriteLine("Enter numbers from 0 to 10. If you want to end please enter nothing"); 
      //while user input something not blank 
      while ((enteredLine = Console.ReadLine()) != string.Empty) 
      { 
       //inputArray has no more elements, resize it 
       if (enteredCount == inputArray.Length) 
       { 
        Array.Resize<int>(ref inputArray, inputArray.Length + 5); 
       } 

       //new entered value to array 
       inputArray[enteredCount] = int.Parse(enteredLine); 
       enteredCount++; 
      } 

      //now we need count all uniq elements 
      //special array. Index is a number from 0 to 10. Value is a count of that value 
      int[] counts = new int[11]; 
      for (int i = 0; i < enteredCount; i++) 
      { 
       int enteredNumber = inputArray[i]; 
       counts[enteredNumber]++; 
      } 

      Console.WriteLine("Totally were entered {0} numbers", enteredCount); 

      //now we now count of each number from 0 to 11. Let' print them 
      for (int i = 0; i < 11; i++) 
      { 
       //Print only numbers, that we entered at least once 
       if (counts[i] != 0) 
        Console.WriteLine("Number {0} were entered {1} times", i, counts[i]); 
      } 

      Console.ReadLine(); 
     } 
+0

Спасибо за объяснения в каждой строке! что действительно помогло мне увидеть цель и разум для каждого сегмента. это было бы похоже на то, что ему просто дали ответ без каких-либо разъяснений или информации о том, почему его право. Большое спасибо за информацию. –

+0

@JoeFredy: Посмотрите еще раз на подсказку pst и помощь Майка! –

+0

Я так и делал, они оба были именно тем, что я искал. Они помогли с тем, что и как. , а @igofed помог с чем и почему. Я изменил некоторые вещи в коде igofed по своему вкусу. –

0

Убедитесь добавить

using System.Collections.Generic; 
using System.Linq; 

Тогда

Console.WriteLine("Distinct values entered & No. of times values entered:"); 

int[] distinctvalues = ScoreArray.Distinct().OrderBy(x => x).ToArray(); 
//Finds distinct values and orders them in ascending order. 

int[] distinctcount = ScoreArray.FindAllIndexof(distinctvalues).ToArray(); 
//Finds how many times distinct values are entered. 

for (int i = 0; i < distinctvalues.Length; i++) 
    Console.WriteLine(distinctvalues[i].ToString() + " --------- Entered " + 
    distinctcount[i].ToString() + " times"); 

Console.Read(); 

Для функции FindAllIndexof создайте Extension Method в static class за пределами вашей Program Класса

public static class EM 
{ 
    public static int[] FindAllIndexof<T>(this IEnumerable<T> values, T[] val) 
    { 
     List<int> index = new List<int>(); 
     for (int j = 0; j < val.Length; j++) 
      index.Add(values.Count(x => object.Equals(x, val[j]))); 
     return index.ToArray(); 
    } 
} 

Выхода

enter image description here

Смежные вопросы