首页 > 解决方案 > 打印 X 以获取 Array 的值

问题描述

我正在尝试为数组中的值打印“x”,例如整数 32 将打印 32 个 x,但我不知道该怎么做。

任何关于做什么的帮助或指示都会很好,但似乎找不到任何对我有帮助的东西而不会使它过于复杂。

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

namespace Histogram
{
    class Program
    {

        static void Main(string[] args)
        {

            string output = "";
            int[] x;
            x = new int[18];

            int[] y = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37, 17, 56, 99, 34, 75, 36, 12, 8, 100, 77 };

            const int ARRAY_SIZE = 18;
            int[] z;

            z = new int[ARRAY_SIZE];

            for (int i = 0; i < z.Length; i++)
                z[i] = 2 * i;              

            Console.WriteLine("Element\t \tValue\t \tHistogram\t\t\n");
            for (int i = 0; i < ARRAY_SIZE; i++)
            {
                output += i + "\t\t" + y[i] + "\t\t" + y[i] + "\t\t" + "\n";                

            }
            Console.WriteLine(output);
            Console.ReadKey();

        }
    }
}

标签: c#arraysconsole-applicationhistogram

解决方案


您正在寻找的内容已经内置到 String 类中。它有一个构造函数来创建一串任意长度的重复字符。不需要 String Builder 或任何额外的循环,这会过于复杂。

 static void Main(string[] args)
 {
      string output = "";
      const int ARRAY_SIZE = 18;
      int[] x = new int[ARRAY_SIZE];
      int[] z = new int[ARRAY_SIZE];
      int[] y = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37, 17, 56, 99, 34, 75, 36, 12, 8, 100, 77 };

      for (int i = 0; i < z.Length; i++)
            z[i] = 2 * i;

      Console.WriteLine("Element\t \tValue\t \tHistogram\t\t\n");
      for (int i = 0; i < ARRAY_SIZE; i++)
      {
           string bar = new string('X', y[i]);
           output += i + "\t\t" + y[i] + "\t\t" + bar + "\t\t" + "\n";
      }
      Console.WriteLine(output);
      Console.ReadKey();
}

推荐阅读