c# - 使用循环未正确平均的数组
问题描述
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(错误)。
我尝试在循环结束时重置数组,但这没有解决任何问题
解决方案
其他人已经指出了这种情况下的问题,但这是在函数顶部声明变量的症状。如果您将它们声明在接近使用它们的位置,那么很明显哪些变量适用于整个函数,哪些具有仅适用于循环内部的范围。
像这样:
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
而不是在两个地方设置变量类型并冒着出错的风险。
推荐阅读
- dynamic - 具有多个变量的动态模态内容
- angular - Angular 6 从服务更新组件
- javascript - 在html报告中单击按钮时如何在单独的窗口中显示图像
- swift - 重新加载集合视图时会发生这种情况
- masstransit - MassTransit Azure - 来自主题错误的接收器
- python - 如何解析具有多个对象的 JSON 文件
- tensorflow - 如何更改现有张量流模型 (.pb) 的输入形状
- powershell - 我可以枚举 VSTS 中的变量组吗?
- sql-server - 如何保存 JMeter 测试结果中显示的准确值,包括最小值、最大值、平均值......?
- lstm - 推理模型在编码器-解码器中重复预测相同的单词