averageHeader = 6-4(4个空字段); 但这不起作用,代码结束tot用红色下划线 我尝试过:I have a windows form with 5 fields of textbox fields,depends on if the field has a mark or not it will calculate the averageFor E.G if first two field only had marks thenAverage = first two field marks calculation/2averageHeader = 6-4(4 empty fields);but this is not working , end of the code tot is underlined with redWhat I have tried:private void button10_Click(object sender, EventArgs e) { int s1, s2, s3, s4, s5, s6; int tot; int avgHeader = 6; if(textBoxS1.Text=="") { avgHeader = avgHeader - 1; } else { s1 = Convert.ToInt16(textBoxS1.Text); tot = tot + s1; } if(textBoxS2.Text=="") { avgHeader = avgHeader - 1; } else { s2 = Convert.ToInt16(textBoxS2.Text); tot=tot+s2; } if (textBoxS3.Text == "") { avgHeader = avgHeader - 1; } else { s3 = Convert.ToInt16(textBoxS3.Text); tot = tot + s3; } if (textBoxS4.Text == "") { avgHeader = avgHeader - 1; } else { s4 = Convert.ToInt16(textBoxS4.Text); tot = tot + s4; } if (textBoxS5.Text == "") { avgHeader = avgHeader - 1; } else { s5 = Convert.ToInt16(textBoxS5.Text); tot = tot + s5; } if (textBoxS6.Text == "") { avgHeader = avgHeader - 1; } else { s6 = Convert.ToInt16(textBoxS6.Text); tot = tot + s6; } int Average = tot / avgHeader; txtaverage.Text = Convert.ToString(Average); }推荐答案试试tryprivate void button10_Click(object sender, EventArgs e) { int tot = 0; int avgHeader = 0; TextBox[] allBox = new TextBox[] { textBoxS1, textBoxS2, textBoxS3, textBoxS4, textBoxS5, textBoxS6 }; foreach (TextBox txt in allBox) if (txt.Text != "") { int temp; int.TryParse(txt.Text.Trim(), out temp); tot += temp; avgHeader++; } int Average = tot / avgHeader; txtaverage.Text = Average.ToString(); } 使用 LINQusing LINQprivate void button10_Click(object sender, EventArgs e) { TextBox[] allBox = new TextBox[] { textBoxS1, textBoxS2, textBoxS3, textBoxS4, textBoxS5, textBoxS6 }; var avg = allBox.Where(k => k.Text != "").Average(k => Convert.ToInt32(k.Text)); txtaverage.Text = avg.ToString(); } 注意:非数字文本格式应在前端验证Note: Non numeric text format should be validated at front end 这篇关于简单的计算问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 09-02 05:25