首页 > 解决方案 > 使用循环未正确平均的数组

问题描述

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

        private void button3_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            StreamReader inputFile;
            int doctor = 0;
            double total = 0, average_sys = 0;
            string name, DocN;

            string[] doctors = new string[3] { "D. ABRAMS, MD", "D. JARVIC, MD", "T. PANOS, MD" };
            int[] systolic = new int[5];
            int[] diastolic = new int[5];

            OpenFileDialog openFile = new OpenFileDialog();

            if (openFile.ShowDialog() == DialogResult.OK)
            {
                inputFile = File.OpenText(openFile.FileName);
                while (!inputFile.EndOfStream)
                {
                    name = inputFile.ReadLine();
                    for (int i = 0; i < 5; i++)
                    {
                        systolic[i] = int.Parse(inputFile.ReadLine());
                        diastolic[i] = int.Parse(inputFile.ReadLine());
                    }

                    //Calculates average for systolic
                    for (int count = 0; count < systolic.Length; count++)
                    {
                        total += systolic[count];
                    }
                    average_sys = total / 5;

                    doctor = int.Parse(inputFile.ReadLine());
                    DocN = doctors[doctor];
                    listBox1.Items.Add(name + "\t" + average_sys + "\t" + DocN);

                }               
            }
        }
    }
}

这是它从中获取的文件

运行程序时,我得到以下收缩压平均值:184.6(正确),312(错误)。

我尝试在循环结束时重置数组,但这没有解决任何问题

标签: c#arraysloopswhile-loop

解决方案


其他人已经指出了这种情况下的问题,但这是在函数顶部声明变量的症状。如果您将它们声明在接近使用它们的位置,那么很明显哪些变量适用于整个函数,哪些具有仅适用于循环内部的范围。

像这样:

                string name = inputFile.ReadLine();

                //Calculates average for systolic
                double total = 0;
                for (int count = 0; count < systolic.Length; count++)
                {
                    total += systolic[count];
                }
                double average_sys = total / 5;

                int doctor = int.Parse(inputFile.ReadLine());
                string DocN = doctors[doctor];
                listBox1.Items.Add(name + "\t" + average_sys + "\t" + DocN);

更好的是,使用var而不是在两个地方设置变量类型并冒着出错的风险。


推荐阅读