从C#数组获取平均值 [英] Getting an average from a C# array

查看:74
本文介绍了从C#数组获取平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经从事这项工作了几天。我自己编写了所有代码。我并不想欺骗别人,也不想找人替我工作,但是为了我的生命,我无法正常工作。

I have been working on this assignment for a couple days now. I have written all the code myself. I'm not looking to cheat or have someone do my work for me, but for the life of me, I can't get this to work correctly.

我遇到的问题是,当我尝试对数组中的数字求平均时,而不是除以条目数,而是除以允许的条目总数

The problem I'm having is that when I try to average numbers in an array, instead of dividing by just the number of entries, it's dividing by the total allowed entries into the array.

例如。我将2个值输入一个可以容纳100个值的数组,而不是除以2,而是除以100。

For example. I enter 2 values into an array that can hold 100 values, instead of dividing by 2, it divides by 100.

如何将其除以数字的条目?这是我所拥有的:

How do I get it to divide by just the number of entries? Here is what I have:

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

namespace ConsoleApplication6
{
    class Program
    {
        static void InputData(string[] player, int[] score, ref int numPlayer)
        {
            // input items up to the number of the array size
            while (numPlayer < player.Length)
            {
                Console.Write("Enter player name (Q to quit): ");
                player[numPlayer] = Console.ReadLine();
                if ((player[numPlayer] == "Q") || (player[numPlayer] == "q"))
                {
                    Console.WriteLine();
                    break;
                }
                else
                {
                    Console.Write("Enter score for " + player[numPlayer] + ": ");
                    score[numPlayer] = Convert.ToInt32(Console.ReadLine());
                    numPlayer++;
                }
            }
        }


        static void DisplayPlayerData(string[] player, int[] score, int numPlayer)
        {
            Console.WriteLine("Name           Score");
            for (int i = 0; i < numPlayer; i++)
                Console.WriteLine("{0, -16} {1, 8}", player[i], score[i]);
        }


        static double CalculateAverageScore(int[] score, ref int numPlayer)
        {
            double avgScore;
            double total = 0;

            for (int i = 0; i < numPlayer; i++)
            {
                total += score[i];
            }
            avgScore = total / score.Length;
            Console.WriteLine("Average Score:" + avgScore);
            return avgScore;
        }

        static void DisplayBelowAverage(string[] player, int[] score, int numPlayer)
        {
            double avgScore = CalculateAverageScore(score, ref numPlayer);
            Console.WriteLine("Players who scored below average");
            Console.WriteLine("Name           Score");
            for (int i = 0; i < numPlayer; i++)
            {
                if (score[i] < avgScore)
                {
                    Console.WriteLine("{0, -16} {1}", player[i], score[i]);
                }
            }
        }
        static void Main(string[] args)
        {
            //Variables
            string[] player = new string[100];
            int[] score = new int[100];
            int numPlayer = 0;

            InputData(player, score, ref numPlayer);
            DisplayPlayerData(player, score, numPlayer);
            CalculateAverageScore(score, ref numPlayer);
            DisplayBelowAverage(player, score, numPlayer);


            Console.ReadLine();
        }
    }
}


推荐答案


  1. 您有一个 numPlayer 变量代表许多输入的玩家。

    只需使用它。 / li>
  1. You have a numPlayer variables that stands for a number of entered players.
    Just use it.

替换

        avgScore = total / score.Length;

        avgScore = total / numPlayer;




  1. 您的代码有一些非常奇怪的地方。 / li>
  1. Your code has some very strange points.

例如,您在计算机中调用 CalculateAverageScore(score,ref numPlayer); Main()。但是,您没有使用返回值。在 DisplayBelowAverage 方法中可以正确调用此方法。
通常来说,它看起来是错误的-引用,具有动态数量的值的静态大小的数组,非格式控制台写入行等。

For example, you call CalculateAverageScore(score, ref numPlayer); in a Main(). However, you are not using a return value. This method is properly called in a DisplayBelowAverage method. In general, it looks wrong - refs, static-sized array with dynamic number of values, non-format console writeline etc.

仅供参考。请阅读一次。也许有些代码行会为您提供帮助。也许您不会找到新的,未知的或有趣的东西。

这就是我要解决的问题:

Just for you information. Read this once. Maybe some code lines will help you. Maybe, you won't find something new, unknown or interesting.
This is how I would solve this problem:

public class Program
{   
    private const string InputTerminationString = "Q";

    public static void Main()
    {
        List<Player> players = new List<Player>(); // p. 1, 4

        while (true)
        {
            Console.Write("Enter player name ({0} to quit): ", InputTerminationString);
            string name = Console.ReadLine();
            if (name == InputTerminationString) break; // p. 2

            Console.Write("Enter score for {0}: ", name); // p. 3
            int score = int.Parse(Console.ReadLine());

            players.Add(new Player { Name = name, Score = score }); 
        }

        Console.WriteLine("Name           Score");
        players.ForEach(x => Console.WriteLine("{0, -16} {1, 8}", x.Name, x.Score)); // p. 5

        double average = players.Average(x => x.Score); // p. 6
        Console.WriteLine("Average score: {0:F2}", average); // p. 3

        Console.WriteLine("Players who scored below average");
        Console.WriteLine("Name           Score");
        players
            .Where(x => x.Score < average) // p. 7
            .ToList()
            .ForEach(x => Console.WriteLine("{0, -16} {1, 8}", x.Name, x.Score)); // p. 5           
    }
}

public class Player
{
    public string Name { get; set; }
    public int Score { get; set; }  
}

现在,逐步:


  1. 使用 Player 类。传递两个独立的名称分数的数组非常不方便。而且,这通常是不安全和适当的。如果是单个玩家,则玩家的姓名和分数是属性,应存储在struct或class中。

  1. Use Player class. It is pretty inconvenient to pass two independent arrays of names and scores. Moreover, it is not safe and proper in general. A name and a score of a player are properties if a single player and should be stored together either in struct or class.

使用常量。如果您需要将'Q'终止字符串更改为'Exit',则可以在一秒钟内完成此操作,而无需浏览代码。

Use constants. If you need to change 'Q' termination string to 'Exit', you will be able to do this in a second without looking through the code.

使用格式为 Console.WriteLine 。它像 String.Format 一样工作,您不需要连接字符串。

这里的一些信息: https://msdn.microsoft.com/en-us/library/828t9b9h(v = vs。 110).aspx

Use formatted Console.WriteLine. It works liks String.Format and you don't need to concatenate strings.
Some info here: https://msdn.microsoft.com/en-us/library/828t9b9h(v=vs.110).aspx

使用动态集合 List 。数组非常适合存储和快速访问已知长度的值范围。由于用户一个一个地输入值,因此您永远不会知道他将输入0、1还是90000个值。 列表集合将为您提供帮助。

此处的一些信息: http://www.dotnetperls.com/list

Use dynamic collection List. Array is good for storing and rapid accessing to range of values of known length. Since a user enters values one by one, you never know if he will enter 0, 1 or 90000 values. List collection will help you with it.
Some info here: http://www.dotnetperls.com/list

您可以使用ForEach方法,该方法为每个代码执行给定的代码集合中的项目。在Lambda表达式中使用ForEach可使代码更短且更具可读性。 .110).aspx rel = nofollow> https://msdn.microsoft.com/en-us/library/bwabdf9z(v = vs.110).aspx

You can use ForEach method which executes the given code for every item in a collection. Using ForEach with lambda-expressions makes code shorter and more readable.
Some info here: https://msdn.microsoft.com/en-us/library/bwabdf9z(v=vs.110).aspx

使用平均值函数来计算集合的平均值。如果 int [] ,则可以使用 arr.Average()。但是,对于 Class 对象,您需要使用lambda-expression描述平均值计算的逻辑。

这里的一些信息: http://www.dotnetperls.com/average

Use Average function which calculates the average of a collection. In case of int[] you can use arr.Average(). However, in case of Class object, you need to describe the logic of calculation of average value using lambda-expression.
Some info here: http://www.dotnetperls.com/average

LINQ 其中表达式可让您过滤集合。

此处的一些信息: http://www.dotnetperls.com/where

LINQ Where expression lets you filter your collection.
Some info here: http://www.dotnetperls.com/where

这篇关于从C#数组获取平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆