C # как усреднить массив ввода - PullRequest
0 голосов
/ 03 апреля 2011

У меня есть первая часть моего кода, достаточно полная, и я понял суть остальных, я просто не уверен, как все это собрать. Вот первая часть

using System;
namespace ConsoleApplication1
{
    class Program
    {
        public class AccountInfo
        {
            public int Number { get; set; }
            public double Balance { get; set; }
            public string LastName { get; set; }
        }

        static void Main(string[] args)
        {
            List<AccountInfo> accounts = new List<AccountInfo>();

            for (int index = 1; index < 6; index++)
            {
                AccountInfo acc = new AccountInfo();

                Console.Write("Enter account number: " + index.ToString() + ": ");
                acc.Number = int.Parse(Console.ReadLine());
                Console.Write("Enter the account balance: ");
                acc.Balance = double.Parse(Console.ReadLine());
                Console.Write("Enter the account holder last name: ");
                acc.LastName = Console.ReadLine();

                accounts.Add(acc);
            }

        }
    }
}

Вторая часть - спросить пользователя, что он хочет делать с массивами


введите a или A для поиска номеров счетов введите b или B, чтобы усреднить счета введите x или X для выхода из программы


поисковая часть, я могу использовать что-то вроде этого:

public void search Accounts()
{
    for(int x = 0; x < validValues.Lenth; ++x)
    {
        if(acctsearched == validValues[x])
        {
            isValidItem = true;
            acctNumber = Number[x];
        }
        }

И я могу использовать цикл while с bool true / false, чтобы закрыться.

Я не уверен, как получить средний баланс. Я получаю сообщения об ошибках типа «не могу неявно изменить int [] на int»

Любая помощь с этим была бы очень признательна.

Ответы [ 2 ]

2 голосов
/ 03 апреля 2011

Похоже, у вас есть список AccountInfo. Вы можете использовать LINQ?

Чтобы получить среднее значение, вы можете сделать это с помощью LINQ:

double avg = accounts.Select(x=>x.Balance).Average(); 

Для поиска данного действия вы можете сделать что-то вроде этого:

var foundAcct = accounts.SingleOrDefault(x=>x.Number==someSearchNum);

Чтобы это работало (и создавались методы для этих двух действий), вам нужно переместить List<AccountInfo> accounts из Main и быть объявленным в классе.

Для LINQ вам потребуется .NET 3.5 или выше.

0 голосов
/ 16 апреля 2011

используя Систему;namespace AssignmentWeek3 {class Accounts {// закрытые члены класса, создающие новые массивы private int [] AcctNumber = new int [5];private double [] AcctBalance = new double [5];приватная строка [] LastName = новая строка [5];

    public void fillAccounts()//fill arrays with user input
    {
        int x = 0;
        for (int i = 0; i < AcctNumber.Length; i++)
        {
            Console.Write("Enter account number: ");              
            AcctNumber[x] = Convert.ToInt32(Console.ReadLine());
            Console.Write("Enter account balance: ");
            AcctBalance[x] = Convert.ToDouble(Console.ReadLine());
            Console.Write("Enter account holder last name: ");
            LastName[x] = Convert.ToString(Console.ReadLine());
            x++;
        } 

    }

    public void searchAccounts() //search account method to be called later in main()
    {
        int accountNum = 0;
        bool isValid = false;
        int x = 0;

        Console.Write("Please enter account number to search for: ");
        accountNum = Convert.ToInt32(Console.ReadLine());


        while (x < AcctNumber.Length && accountNum != AcctNumber[x])
            ++x;
        if(x != AcctNumber.Length)
        {
        isValid = true;
        }
        if(isValid){
        Console.WriteLine("AcctNumber: {0}      Balance: {1:c}  Acct Holder: {2}", AcctNumber[x], AcctBalance[x], LastName[x]);
        }
        else{  
            Console.WriteLine("You entered an invalid account number"); 
        }                    
    }

    public void averageAccounts()//averageAccounts method to be store for later use
    {
        // compute and display average of all 5 bal as currency use length.
        int x = 0;
        double balanceSum = 0;
        double Avg = 0;

        for (x = 0; x < 5; x++ )
        {
            balanceSum = balanceSum + AcctBalance[x];
        }
        Avg = (balanceSum / x);
        Console.WriteLine("The average balance for all accounts is {0:c}", Avg);
    } 

} //end public class Accounts

class week3_assignment // Основной класс {static void Main () {char entry = '0';

       //instantiate one new Accounts object
       Accounts accounts = new Accounts();

       //call class methods to fill Accounts
       accounts.fillAccounts();

       //menu with input options
       bool Exit = false;
       while (!Exit)   
       {
       while (entry != 'x' && entry != 'X')
       {


           Console.WriteLine("*****************************************");
           Console.WriteLine("enter an a or A to search account numbers");
           Console.WriteLine("enter a b or B to average the accounts");
           Console.WriteLine("enter an x or X to exit program");
           Console.WriteLine("*****************************************");


          entry = Convert.ToChar(Console.ReadLine());

               switch (entry)  //set switch
               {
                   case 'a':
                   case 'A':
                       accounts.searchAccounts();//calls search accounts method
                       break;
                   case 'b':
                   case 'B':
                       accounts.averageAccounts();//calls average accounts method
                       break;
                   case 'x':
                   case 'X':
                       (Exit) = true;
                       break;
                   default:
                        Console.WriteLine("That is not a valid input");
                       break;
               }
           }  
       }    
   } 

}}

...