C# Как подсчитать количество входных данных, чтобы найти среднее значение в цикле переключения?

Вот мой цикл, который запрашивает номер группы, а затем пожертвование. Мне интересно, как подсчитать количество пожертвований, чтобы найти среднее значение для каждой группы.

using System;
public class TotalPurchase
{
    public static void Main()
    {

    double total4 = 0;
    double total5 = 0;
    double total6 = 0;
    int myint = -1;

    while (myint != 0)
    {
        string group;

        Console.WriteLine("Please enter group number (4, 5, or 6)");
        Console.WriteLine("(0 to quit): ");
        group = Console.ReadLine();
        myint = Int32.Parse(group);

        switch (myint)
        {
            case 0:
                break;
            case 4:
                double donation4;
                string inputString4;
                Console.WriteLine("Please enter the amount of the contribution: ");
                inputString4 = Console.ReadLine();
                donation4 = Convert.ToDouble(inputString4);
                total4 += donation4;
                break;
            case 5:
                double donation5;
                string inputString5;
                Console.WriteLine("Please enter the amount of the contribution: ");
                inputString5 = Console.ReadLine();
                donation5 = Convert.ToDouble(inputString5);
                total5 += donation5;
                break;
            case 6:
                double donation6;
                string inputString6;
                Console.WriteLine("Please enter the amount of the contribution: ");
                inputString6 = Console.ReadLine();
                donation6 = Convert.ToDouble(inputString6);
                total6 += donation6;
                break;
            default:
                Console.WriteLine("Incorrect grade number.", myint);
                break;
        }
    }

    Console.WriteLine("Grade 4 total is {0}", total4.ToString("C"));
    Console.WriteLine("Grade 5 total is {0}", total5.ToString("C"));
    Console.WriteLine("Grade 6 total is {0}", total6.ToString("C"));

    }
}

Любая помощь будет оценена по достоинству.


person Joel    schedule 27.03.2011    source источник


Ответы (6)


using System;

public class TotalPurchase
{
    public static void Main()
    {
       double total4 = 0;
       double total5 = 0;
       double total6 = 0;

       int numberOfInputForTotal4 = 0;
       int numberOfInputForTotal5 = 0;
       int numberOfInputForTotal6 = 0;

       int myint = -1;

        while (myint != 0)
        {
            string group;

            Console.WriteLine("Please enter group number (4, 5, or 6)");
            Console.WriteLine("(0 to quit): ");
            group = Console.ReadLine();
            myint = Int32.Parse(group);

            switch (myint)
            {
                case 0:
                    break;
                case 4:
                    double donation4;
                    string inputString4;
                    Console.WriteLine("Please enter the amount of the contribution: ");
                    inputString4 = Console.ReadLine();
                    donation4 = Convert.ToDouble(inputString4);
                    total4 += donation4;
                    numberOfInputForTotal4++;
                    break;
                case 5:
                    double donation5;
                    string inputString5;
                    Console.WriteLine("Please enter the amount of the contribution: ");
                    inputString5 = Console.ReadLine();
                    donation5 = Convert.ToDouble(inputString5);
                    total5 += donation5;
                    numberOfInputForTotal5++;
                    break;
                case 6:
                    double donation6;
                    string inputString6;
                    Console.WriteLine("Please enter the amount of the contribution: ");
                    inputString6 = Console.ReadLine();
                    donation6 = Convert.ToDouble(inputString6);
                    total6 += donation6;
                    numberOfInputForTotal6++;
                    break;
                default:
                    Console.WriteLine("Incorrect grade number.", myint);
                    break;
            }
        }

        Console.WriteLine("Grade 4 total is {0}", total4.ToString("C"));
        Console.WriteLine("Grade 5 total is {0}", total5.ToString("C"));
        Console.WriteLine("Grade 6 total is {0}", total6.ToString("C"));

        Console.WriteLine("Grade 4 average is {0}", (total4 / numberOfInputForTotal4).ToString("C"));
        Console.WriteLine("Grade 5 average is {0}", (total5 / numberOfInputForTotal5).ToString("C"));
        Console.WriteLine("Grade 6 average is {0}", (total6 / numberOfInputForTotal6).ToString("C"));

    }
}

Как видите, есть 3 дополнительные переменные (по одной для каждой группы), которые можно использовать для определения количества предоставленных входных данных. Используя это, вы можете разделить общее количество для каждой группы на количество входов в каждой группе отдельно.

person shahkalpeshp    schedule 27.03.2011

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

int donations4 = 0;
int donations5 = 0;
int donations6 = 0;

А затем увеличивайте этот счетчик в каждом из ваших случаев переключения, например:

switch(myInt)
{
   case 4:
     ...
     donations4++;
     break;
   case 5:
     ...
     donations5++;
     break;
   case 6:
     ...
     donations6++;
     break;
}

Затем, когда вы закончите, просто сделайте математику, чтобы найти среднее значение.

Хотя это, вероятно, самый простой способ, лучшим способом было бы рассматривать каждую группу как отдельный объект, и объект должен внутренне отслеживать количество пожертвований, а также сумму и среднее значение.

-- Дэн

person debracey    schedule 27.03.2011

Просто объявите количество для каждой группы, а также общее количество и приращение в операторе case:

case 4:
            double donation4;
            string inputString4;
            Console.WriteLine("Please enter the amount of the contribution: ");
            inputString4 = Console.ReadLine();
            donation4 = Convert.ToDouble(inputString4);
            total4 += donation4;
            count4++; // HERE!!!!
            break;

В качестве альтернативы вы можете использовать List<int>, который также рассчитает ваше среднее значение:

 List<int> list4 = new List<int>();

а также

case 4:
            double donation4;
            string inputString4;
            Console.WriteLine("Please enter the amount of the contribution: ");
            inputString4 = Console.ReadLine();
            donation4 = Convert.ToDouble(inputString4);
            list4.Add(donation4);
            break;

а также

 Console.WriteLine(list4.Average());
person Aliostad    schedule 27.03.2011

Просто следите за счетчиком с помощью другой переменной. count4, count5 и т. д.

person Kyte    schedule 27.03.2011

Для бонусных баллов за домашнее задание:

1) Очистите ввод номера вашей группы, т.е. проверьте, ввел ли пользователь действительный номер.

2) Не вызывайте переменную myInt. Назовите его groupNum или что-то, что описывает функцию, а не реализацию переменной.

3) Используйте массив для сумм и подсчетов пожертвований, т.е.

int[] donationCount= new int[MAX_GROUP+1];    // figure out yourself why the +1
int[] donationTotal= new int[MAX_GROUP+1];
// initialize donationCount and donationTotal here

затем в вашем цикле (даже не нужен переключатель):

++donationCount[groupNum];
donationTotal[groupNum] += donationAmount;    // did you notice that you moved the reading of donationAmount out of the switch?
person dar7yl    schedule 27.03.2011

Я бы пошел с изменением ваших двойников на список и использованием методов Sum() и Average() в ваших списках в конце. Ваш код будет выглядеть так после этого изменения.

    using System;
using System.Collections.Generic;
using System.Linq;
public class TotalPurchase
{
    public static void Main()
    {

        List<double> total4 = new List<double>();
        List<double> total5 = new List<double>();
        List<double> total6 = new List<double>();
        int myint = -1;

        while (myint != 0)
        {
            string group;

            Console.WriteLine("Please enter group number (4, 5, or 6)");
            Console.WriteLine("(0 to quit): ");
            group = Console.ReadLine();
            myint = Int32.Parse(group);

            switch (myint)
            {
                case 0:
                    break;
                case 4:
                    double donation4;
                    string inputString4;
                    Console.WriteLine("Please enter the amount of the contribution: ");
                    inputString4 = Console.ReadLine();
                    donation4 = Convert.ToDouble(inputString4);
                    total4.Add(donation4);
                    break;
                case 5:
                    double donation5;
                    string inputString5;
                    Console.WriteLine("Please enter the amount of the contribution: ");
                    inputString5 = Console.ReadLine();
                    donation5 = Convert.ToDouble(inputString5);
                    total5.Add(donation5);
                    break;
                case 6:
                    double donation6;
                    string inputString6;
                    Console.WriteLine("Please enter the amount of the contribution: ");
                    inputString6 = Console.ReadLine();
                    donation6 = Convert.ToDouble(inputString6);
                    total6.Add(donation6);
                    break;
                default:
                    Console.WriteLine("Incorrect grade number.", myint);
                    break;
            }
        }

        if(total4.Count > 0)
            Console.WriteLine("Grade 4 total is {0}; Average {1}", total4.Sum().ToString("C"), total4.Average().ToString("C"));
        if(total5.Count >0)
            Console.WriteLine("Grade 5 total is {0}; Average {1}", total5.Sum().ToString("C"), total5.Average().ToString("C"));
        if (total6.Count > 0)
            Console.WriteLine("Grade 6 total is {0}; Average {1}", total6.Sum().ToString("C"), total6.Average().ToString("C"));

    }
}
person Greg Andora    schedule 28.03.2011