【问题标题】:Can't print index and sum of an array无法打印数组的索引和总和
【发布时间】:2020-01-18 02:52:06
【问题描述】:

我有作业。我必须制作一个程序,它可以输入数组的长度和其中的值。单击“处理”按钮后,程序将输出索引和值以及数组中的结果总和和平均值。

我卡住了,无法将索引和值打印到进程按钮下方的多个文本框中。

我希望输出如下所示:

这是我目前成功编写的代码:

namespace ArrayProcess
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void process_Click(object sender, EventArgs e)
        {

            int sum = 0;
            string ind = "index";
            string message;
            int count = Convert.ToInt32(inputArray.Text);
            int[] varray = new int[count];
            for (int i=1; i <= count; i++)
            {
                varray[i] = Convert.ToInt32(Interaction.InputBox(message="enter the value of array number "+i));
                sum += varray[i];
            }
            boxSum.Text = Convert.ToString(sum);
        }
    }
}

请帮帮我。

【问题讨论】:

标签: c#


【解决方案1】:

这是给你的代码(boxAvg 是平均值)

namespace ArrayProcess
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void process_Click(object sender, EventArgs e)
        {

            int sum = 0;
            string ind = "index";
            string message;
            int count = Convert.ToInt32(inputArray.Text);
            int[] varray = new int[count];
            for (int i=1; i <= count; i++)
            {
                varray[i-1] = Convert.ToInt32(Interaction.InputBox(message="enter the value of array number "+i));
                sum += varray[i-1];
            }
            //Refer your list box here to add newly added values to the list
            boxSum.Text = Convert.ToString(sum);
            boxAvg.Text = Convert.ToString(sum / count);  //calculate the average
        }
    }
}

【讨论】:

    【解决方案2】:

    鉴于数组已经有数据:

    private void Display()
    {
        var columnHeader1 = "Index    Value\n";
        multilineTextBox1.Text = 
            columnHeader1 +
            string.Join("\n", vArray.Select((x,i)=> $"{i+1,5}    {x,5}"));
    
    
        boxSum.Text = vArray.Sum(); 
        boxAvg.Text = vArray.Average();
    
    
        var columnHeader2 = "Index    Value    Histogram\n";
        multilineTextBox2.Text = 
            columnHeader2 + 
            string.Join("\n", vArray.Select((x,i)=> $"{i+1,5}    {x,5}    {new String('*', x)}"));
    }
    

    Console demo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-18
      • 2020-12-26
      • 1970-01-01
      • 2019-04-21
      • 1970-01-01
      相关资源
      最近更新 更多