带直方图的 C# 级数组

Voj*_*ech 5 c# arrays

我正在瑞典学习 C# 基础编程,我想知道您是否可以帮助我理解一个简单的示例。

我的目标是用随机数填充数组,然后显示星号 (*) 或任何符号,其次数与随机生成的数字相同。

这就是我的意思:

Student 1 has a grade: 4 : * * * *
Student 2 has a grade: 9 : * * * * * * * * *
etc.
Run Code Online (Sandbox Code Playgroud)

这是我到目前为止想出的代码:

using System;
using System.Text;

namespace Array_1_10
{
    class Program
    {
        static void Main(string[] args)
        {
            //declar and create an int array object with 5 elements

            string tempStars = "";
            int[] grades = new int[11];
            // initiate the array using Random class methods
            Random grade = new Random();
            for (int j = 1; j < 11; j++)
                grades[j] = grade.Next(1, 9);
            //Read and display the array's elements

            for (int j = 1; j < 11; j++)
            {
                tempStars += "*" + " ";

                tempStars += "";
                Console.WriteLine("Student {0} has got: {1} : {2} ", j, grades[j], tempStars);
            }   
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

它会填充数组,但无论生成什么数字,星号都会从 1 到 10,如下所示:

Student 1 has a grade 5 : *
Student 2 has a grade 1 : * *
etc.
Run Code Online (Sandbox Code Playgroud)

你能帮我解决这个问题吗?非常感谢。沃伊泰克

Kev*_*tch 1

您需要更改显示星星数量的代码以考虑等级。所以 for 循环的代码是:

For(j=1; j<11; j++)
{
    StringBuilder ab = new StringBuilder(grades[j]);
    For(int i=0; i<grades[j]; i++)
    {
        sb.Append(" *");
    }

    Console.WriteLine("Student {0} has grade {1} : {2}", j, grades[j], sb.ToString());

}
Run Code Online (Sandbox Code Playgroud)

额外的 for 循环是用学生获得的星星数量构建一个字符串。您应该使用字符串生成器来执行此类操作,因为它比创建大量字符串要高效得多。

需要注意的一件事是代码将字符串生成器初始化为正确的字符串长度。这节省了字符串构建器类在用于构建字符串的引擎盖下调整其数组大小的工作。