简体   繁体   English

生成带有随机数的列表。 排序和总和

[英]Generate list with random numbers. Sort and total sum

I am new to programming and i would be delighted if someone could help me with the following problem. 我是编程新手,如果有人可以帮助我解决以下问题,我将非常高兴。 I have problem with two methods. 我有两种方法的问题。 First sum all of 50 random numbers in a list, second sort list with 50 random numbers. 首先将列表中的所有50个随机数相加,然后将50个随机数与第二个排序列表相加。 I know how to do this when a list has for example four numbers{1,2,3,8} , but not with 50 random numbers. 我知道当列表有四个数字{1,2,3,8}却没有50个随机数时该怎么做。

It will be nice to use a constructor to this two methods, but I don't now how to do this. 最好为这两个方法使用构造函数,但是现在我不知道如何做到这一点。

Any help would be much appreciated. 任何帮助将非常感激。

class Class1
{
  var rand = new Random();

  public Class1( ) //  how to use a constructor ?


    public static List<double> TotalSum()
    {

        var alist = new List<double>();
        for (int i = 0; i < 50; i++)
        {
            alist.Add(rand.Next(10));
        }
        Console.WriteLine("Total sum:", alist);
    }

    public static List<double> Sort()
    {
        var slist = new List<double>();
        for (int i = 0; i < 50; i++)
        {
            slist.Sort(rand.Next(10));   // rand.Next does not work with Sort
            Console.WriteLine(slist);
        }
    }


    class Program
    {
        static void Main(string[] args)
        {
            Class1 show = new Class1(); 
            show.TotalSum();
            show.Sort();
        }
    }
}

just use the 2 methods 只需使用2种方法

list.Sum(); 
list.Sort();

I suggest that you use rand.Next(Environment.TickCount) to get better random numbers, but at the end you need to use a different primitive value to store the result 我建议您使用rand.Next(Environment.TickCount)获得更好的随机数,但是最后您需要使用其他原始值来存储结果

class Program
{
    static void Main(string[] args)
    {
        var array = Class1.Sort();
        PrintArray(array);

        Console.WriteLine();

        Console.WriteLine("Total sum: {0}", Class1.TotalSum());

        Console.ReadLine();
    }

    static void PrintArray(List<double> array)
    {
        foreach (var a in array)
            Console.WriteLine(a);
    }
}

public class Class1
{

    public static double TotalSum()
    {
        var rand = new Random();

        var alist = new List<double>();
        for (int i = 0; i < 50; i++)
        {
            alist.Add(rand.Next(10));
        }

        return alist.Sum();
    }

    public static List<double> Sort()
    {
        var rand = new Random();

        var slist = new List<double>();
        for (int i = 0; i < 50; i++)
        {
            slist.Add(rand.Next(10)); // rand.Next does not work with Sort
        }

        slist.Sort();

        return slist;
    }
}

I think I got what you mean. 我想我明白你的意思。 You want a class that holds random list of numbers and you need some functions. 您需要一个包含随机数字列表的类,并且需要一些函数。

Its better to give more suitable name to your class. 最好给您的班级起一个更合适的名字。 for example "RandomList" would be good. 例如“ RandomList”会很好。

You can't use Console.WriteLine(list) to print items of list. 您不能使用Console.WriteLine(list)打印列表项。 You have to iterate through items and print them in the way you want. 您必须遍历所有项目并以所需方式打印它们。

You can't use var to define fields. 您不能使用var来定义字段。 You have to write the type explicitly. 您必须显式地编写类型。

static keyword in other word is one for all instances . 换句话说, static关键字one for all instances So if you dont use static it would be one per instance . 因此,如果您不使用静态,则one per instanceone per instance Instance is just the object that you create with the constructor. 实例只是您使用构造函数创建的对象。 Its better to declare random number generator as static, but other methods and list field should remain non static. 最好将随机数生成器声明为静态,但其他方法和列表字段应保持非静态。

With the use of Linq Sum() you can get the sum of all the items from list. 使用Linq Sum()您可以从列表中获取所有项目的总和。 If you dont want to use Linq then you have to iterate through list and add each item to value sum . 如果您不想使用Linq,则必须遍历list并将每个项目添加到value sum

I commented the code to explain things. 我注释了代码以解释事情。

class Program
{
    static void Main(string[] args)
    {
        RandomList show = new RandomList(50, 10);
        show.TotalSum();
        show.Sort();
    }
}
class RandomList
{
    private static Random rand = new Random();

    private List<double> _list; // this field holds your list

    public RandomList(int length , int maxValuePerItem) // this is the constructor
    {
        _list = new List<double>(); 

        // populate list
        for (int i = 0; i < length; i++)
        {
            _list.Add(rand.Next(maxValuePerItem)); 
        }
    }

    public void TotalSum()
    {
        Console.WriteLine("Total sum: {0}", _list.Sum()); // {0} is required to specify the place to put _list.Sum() inside string.


        // without linq way
        // int sum = 0;
        // foreach(var i in _list) sum += i;
    }

    public void Sort()
    {
        _list.Sort();

        foreach (var d in _list) 
        {
            Console.Write(d + " , "); // you need to print this in the way you want.
        }
    }
}

A constructor is typically used to initialize some values. 通常使用构造函数来初始化一些值。 In your case, you should use it to initialize your list, that is, to load it with 50 random numbers. 在您的情况下,应使用它来初始化列表,即为它加载50个随机数。 We will also change it so that the list is a property of the class. 我们还将对其进行更改,以使列表成为该类的属性。

Note that the methods shouldn't be static, since they are acting on a property of the class. 请注意,方法不应是静态的,因为它们作用于类的属性。 We are also using the built-in methods of List ( Sum() and Sort() ) instead of rolling our own. 我们还使用List的内置方法( Sum()Sort() ),而不是滚动自己的方法。

class Class1
{
    var rand = new Random();
    var alist;

    public Class1() // constructor creates a new list and initializes it
    {
        alist = new List<double>();
        for (int i = 0; i < 50; i++)
        {
            alist.Add(rand.Next(10)); 
        }
    }


    public List<double> TotalSum()
    {
        Console.WriteLine("Total sum:", alist.Sum());
    }

    public List<double> Sort()
    {
        alist.Sort();   
        for (double num in alist)
        {
            Console.WriteLine(num.ToString());
        }

    }


    class Program
    {
        static void Main(string[] args)
        {
            Class1 show = new Class1();
            show.TotalSum();
            show.Sort();
        }
    }
}

Because you asked how to use the constructor I tried to rewrite your code in a way that the constructor do something of usefull. 因为您询问了如何使用构造函数,所以我试图以构造函数执行一些有用的方式来重写代码。 I added a property and a local variable plus another function. 我添加了一个属性和一个局部变量以及另一个函数。

public class Class1
    {
        Random rand = new Random();
        List<double> alist { get; set; }

        public Class1(int howmany = 50)
        {
            alist = new List<double>();
            for (var i = 0; i < howmany; i++)
            {
                alist.Add(rand.NextDouble());
            }
        }

        public void Sort()
        {
            alist.Sort();
        }

        public void printTotalSum()
        {
            Console.WriteLine("Total sum: {0}", alist.Sum());
        }

        public void printList() {
            Console.WriteLine("The list contains:");
            for (int i = 0; i < alist.Count; i++)
            {
                Console.WriteLine(alist[i]);
            }
        }

    }

   class Program
    {
        static void Main(string[] args)
        {

            Class1 show = new Class1(10);
            show.printTotalSum();
            show.Sort();
            show.printList();
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM