C# 使用C语言的评分表#
我试图用C#制作一个.NET成绩表,我遇到的问题是我得到的平均值是错误的。尽管我试图在许多不同的循环中计算总数,但结果却不正确。有时太高,有时太低。当我尝试在验证循环中计算总分时,它显示了一些奇怪的高值总和,而当我尝试在计算函数中计算总和时,总和太低。请帮忙C# 使用C语言的评分表#,c#,.net,C#,.net,我试图用C#制作一个.NET成绩表,我遇到的问题是我得到的平均值是错误的。尽管我试图在许多不同的循环中计算总数,但结果却不正确。有时太高,有时太低。当我尝试在验证循环中计算总分时,它显示了一些奇怪的高值总和,而当我尝试在计算函数中计算总和时,总和太低。请帮忙 namespace SemesterGradesForm { public partial class formSemesterGrades : Form { TextBox[] inputTextBoxes
namespace SemesterGradesForm
{
public partial class formSemesterGrades : Form
{
TextBox[] inputTextBoxes;
TextBox[] outputTextBoxes;
double totalMarks;
public formSemesterGrades()
{
InitializeComponent();
inputTextBoxes = new TextBox[] { textBoxCourse1Marks, textBoxCourse2Marks, textBoxCourse3Marks, textBoxCourse4Marks, textBoxCourse5Marks, textBoxCourse6Marks, textBoxCourse7Marks };
outputTextBoxes = new TextBox[] { textBoxCourse1LetterGrade, textBoxCourse2LetterGrade, textBoxCourse3LetterGrade, textBoxCourse4LetterGrade, textBoxCourse5LetterGrade, textBoxCourse6LetterGrade, textBoxCourse7LetterGrade };
}
/// <summary>
/// Compare a given numeric grade value to an array of grades to determine a letter representing that grade.
/// </summary>
/// <param name="numericGrade"> A grde between 0 and 100</param>
/// <returns>Letter grade as a short string</returns>
private string GetLetterGrade(double numericGrade)
{
// Declare arrays for the grade values and letter values that corresponds.
double[] gradeValues = { 0D, 50D, 52D, 58D, 60D, 62D, 68D, 70D, 72D, 78D, 80D, 82D, 90D };
string[] gradeLetters = { "F", "D-", "D", "D+", "C-", "C", "C+", "B-", "B", "B+", "A-", "A", "A+" };
// Default the return letter to F
string returnLetter = "F";
// Count through the array comparing grades to the input grade.
for (int counter = 0; counter < gradeValues.Length; counter++)
{
// if the niput grade is bigger than the value in the array, assign the letter grade.
if (numericGrade > gradeValues[counter])
{
returnLetter = gradeLetters[counter];
}
// If the input grade is not bigger than the value in the arraym return the last assigned letter grade
else
{
return returnLetter;
}
}
return returnLetter;
}
/// <summary>
/// Check if a passed TexBox is a numeric grade between 0 and 100
/// </summary>
/// <param name="boxToCheck"> A textbox to check for a valid numeric grade value</param>
/// <returns> true if valid </returns>
private bool IsTextBoxValid(TextBox boxToCheck)
{
const double MinimumGrade = 0.0;
const double MaximumGrade = 100.0;
double gradeValue = 0;
if (double.TryParse(boxToCheck.Text, out gradeValue))
{
if (gradeValue >= MinimumGrade && gradeValue <= MaximumGrade)
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
/// <summary>
/// Clears fields and sets the form to its default state
/// </summary>
private void SetDefaults()
{
// Clear All input controls.
ClearControls(inputTextBoxes);
//Clear all output controls.
ClearControls(outputTextBoxes);
textBoxSemesterMarks.Clear();
textBoxSemesterLetterGrade.Clear();
textBoxOutput.Clear();
// Reset variable
totalMarks = 0;
//Set focus in some useful way
textBoxCourse1Marks.Focus();
// Re-enable controls
buttonCalculate.Enabled = true;
SetControlsEnabled(inputTextBoxes, true);
}
/// <summary>
/// Mass clears the text boxes
/// </summary>
/// <param name="controlArray">An array of controls with a text property to clear</param>
private void ClearControls(Control[] controlArray)
{
foreach (Control controlToClear in controlArray)
{
controlToClear.Text = String.Empty;
}
}
/// <summary>
/// TODO: You should comment this - what does it do?
/// </summary>
/// <param name="controlArray">An array of controls to enable or disable</param>
/// <param name="enabledStatus">true to enable, false to disable</param>
private void SetControlsEnabled(Control[] controlArray, bool enabledStatus)
{
foreach (Control controlToSet in controlArray)
{
controlToSet.Enabled = enabledStatus;
}
}
/// <summary>
/// When youn leave one of the textboxes
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LeaveInputTextbox (object sender, EventArgs e)
{
// Count through all of the textboxes.
for( int inputCounter = 0; inputCounter < inputTextBoxes.Length; inputCounter++ )
{
// Determine if the textbox's contents are valid.
if (IsTextBoxValid(inputTextBoxes[inputCounter]))
{
double grade;
// Get the letter grade from this textbox
grade = double.Parse(inputTextBoxes[inputCounter].Text);
// Assign this letter grade to the corresponding label.
outputTextBoxes[inputCounter].Text = GetLetterGrade(grade);
}
}
}
private void formSemesterGrades_Load(object sender, EventArgs e)
{
}
private void buttonReset_Click(object sender, EventArgs e)
{
SetDefaults();
}
private void buttonCalculate_Click(object sender, EventArgs e)
{
double averageMarks = 0;
int invalidBox = 0;
int validBox = 0;
for (int inputCounter = 0; inputCounter < inputTextBoxes.Length; inputCounter++)
{
if (IsTextBoxValid(inputTextBoxes[inputCounter]))
{
totalMarks += double.Parse(inputTextBoxes[inputCounter].Text);
// Increase counter
inputCounter++;
// If the textbox is valid, count it. If not, just don't.
validBox++;
}
else
{
// If the box is not blank, increment the number of invalid boxes by one.
if(String.IsNullOrEmpty(inputTextBoxes[inputCounter].Text) == false)
{
// Focus on invalid input
inputTextBoxes[inputCounter].Focus();
textBoxOutput.Text = "Please enter VALID Values!";
// Increase invalid counter
invalidBox++;
}
}
}
// If number of valid boxes == 1 && number of invalid boxes == 0
if (validBox >= 1 && invalidBox == 0)
{
// Calculate and output the average
averageMarks = Math.Round(totalMarks / inputTextBoxes.Length, 2);
// Display the Average marks and grade
textBoxSemesterMarks.Text = averageMarks.ToString();
// Assign this letter grade to the corresponding label.
double grade;
grade = double.Parse(textBoxSemesterMarks.Text);
textBoxSemesterLetterGrade.Text = GetLetterGrade(grade);
// Disable input controls until the form is reset.
buttonCalculate.Enabled = false;
SetControlsEnabled(inputTextBoxes, false);
buttonReset.Focus();
}
else
{
textBoxOutput.Text = "Please enter VALID Values!";
}
}
private void buttonExit_Click(object sender, EventArgs e)
{
Close();
}
}
}
名称空间SemesterGradesForm
{
公共部分类表单等级:表单
{
文本框[]输入文本框;
TextBox[]输出textboxs;
双重总分;
公共表格高级程度()
{
初始化组件();
InputTextBox=新建TextBox[]{textBoxCourse1Marks,textBoxCourse2Marks,textBoxCourse3Marks,textBoxCourse4Marks,textBoxCourse5Marks,textBoxCourse6Marks,textBoxCourse7Marks};
outputTextBoxes=新文本框[]{textBoxCourse1LetterGrade,textBoxCourse2LetterGrade,textBoxCourse3LetterGrade,textBoxCourse4LetterGrade,textBoxCourse5LetterGrade,textBoxCourse6LetterGrade,textBoxCourse7LetterGrade};
}
///
///将给定的数值等级值与等级数组进行比较,以确定表示该等级的字母。
///
///介于0和100之间的grde
///字母等级为短字符串
专用字符串GetLetterGrade(双数级)
{
//为相应的等级值和字母值声明数组。
双[]等级值={0D、50D、52D、58D、60D、62D、68D、70D、72D、78D、80D、82D、90D};
字符串[]等级字母={“F”、“D-”、“D”、“D+”、“C-”、“C”、“C+”、“B-”、“B”、“B+”、“A-”、“A+”};
//默认返回字母为F
字符串returnLetter=“F”;
//通过将等级与输入等级进行比较的数组进行计数。
用于(int计数器=0;计数器等级值[计数器])
{
returnLetter=成绩字母[计数器];
}
//如果输入等级不大于arraym中的值,则返回最后指定的字母等级
其他的
{
回信;
}
}
回信;
}
///
///检查通过的文本框是否为介于0和100之间的数值等级
///
///用于检查有效数值等级值的文本框
///如果有效,则为true
私有bool IsTextBoxValid(TextBox-boxToCheck)
{
常数双最小等级=0.0;
const-double-MaximumGrade=100.0;
双梯度值=0;
if(double.TryParse(boxToCheck.Text,out-grade值))
{
如果(gradeValue>=MinimumGrade&&gradeValue=1&&invalidBox==0)
{
//计算并输出平均值
averageMarks=Math.Round(totalMarks/InputTextBox.Length,2);
//显示平均分数和等级
textBoxSemesterMarks.Text=averageMarks.ToString();
//将此字母等级指定给相应的标签。
双级;
grade=double.Parse(textBoxSemesterMarks.Text);
textBoxSemesterLetterGrade.Text=GetLetterGrade(grade);
//禁用输入控件,直到窗体重置。
buttonCalculate.Enabled=false;
SetControlsEnabled(InputExtBox,false);
按钮设置焦点();
}
其他的
{
textBoxOutput.Text=“请输入有效值!”;
}
}
私有无效按钮单击(对象发送者,事件参数e)
{
Close();
}
}
}
我认为你发的代码太多了,因为问题涉及到班级平均成绩的计算
从根本上说,您是在UI元素(如文本框)中以字符串的形式存储成绩,因此无法直接与数据交互,除非您始终保持从字符串到值的转换
我建议您创建一个C#对象(一个类)来存储名为class
的类等级,并让它处理所有逻辑。在这种情况下,您可以使用内置的.Average()
方法作为System.Linq
的一部分,该方法返回任何数字集合的平均值
在下面的示例中,我生成以下输出:
Class: Art I
---
Student Score Grade
Alex 48 F
Beatrice 56 D
Claire 65 C
Dennis 78 B+
Eugene 82 A
Forest 88 A
Gwen 98 A+
---
Average 73.6 B
来自以下示例代码:
static void Main(string[] args)
{
var art = new Class("Art I",
"Alex", "Beatrice", "Claire",
"Dennis", "Eugene", "Forest",
"Gwen");
art.SetGrade("Alex", 48m);
art.SetGrade("Beatrice", 56m);
art.SetGrade("Claire", 65m);
art.SetGrade("Dennis", 78m);
art.SetGrade("Eugene", 82m);
art.SetGrade("Forest", 88m);
art.SetGrade("Gwen", 98m);
Console.WriteLine($"Class: {art.Title}");
Console.WriteLine("---");
Console.WriteLine($"{"Student",12} {"Score",8} {"Grade",8}");
foreach (var grade in art.Grades)
{
Console.WriteLine($"{grade.Key,12} {grade.Value,8} {Class.GetLetterGrade(grade.Value),8}");
}
Console.WriteLine("---");
Console.WriteLine($"{"Average",12} {art.AverageScore,8} {Class.GetLetterGrade(art.AveragScore),8}");
}
这里的关键是方法Class.AverageScore
和字母分数,它们依赖于静态函数Class.GetLetterGrade()
实际逻辑由定义为的类对象处理
public class Class
{
public Class(string title, params string[] students)
{
Title = title;
grades = new Dictionary<string, decimal>();
foreach (var student in students)
{
grades[student] = 0m;
}
}
public string Title { get; }
public IReadOnlyCollection<string> Students { get => grades.Keys.ToList(); }
public void SetGrade(string student, decimal score)
{
if (grades.ContainsKey(student))
{
this.grades[student] = score;
}
else
{
throw new ArgumentException("Student not found", nameof(student));
}
}
readonly Dictionary<string, decimal> grades;
public IReadOnlyDictionary<string, decimal> Grades { get => grades; }
public decimal AverageScore { get => Math.Round(grades.Values.Average(),1); }
#region Grading
// Declare arrays for the grade values and letter values that corresponds.
static readonly decimal[] gradeValues = { 0, 50, 52, 58, 60, 62, 68, 70, 72, 78, 80, 82, 90 };
static readonly string[] gradeLetters = { "F", "D-", "D", "D+", "C-", "C", "C+", "B-", "B", "B+", "A-", "A", "A+" };
public static string GetLetterGrade(decimal score)
{
// use rounding rules
score = Math.Round(score, 0, MidpointRounding.AwayFromZero);
if (score > 100m) { score = 100m; } // max 100
int index = Array.IndexOf(gradeValues, gradeValues.LastOrDefault((x) => score >= x));
if (index < 0) { index = 0; } // default "F"
return gradeLetters[index];
}
public static decimal GetScoreFromLetter(string grade)
{
int index = Array.IndexOf(gradeLetters, grade);
if (index <= 0) { index = 0; } // default "0"
return gradeValues[index];
}
#endregion
}
公共类
{
公共类(字符串标题,参数字符串[]学生)
{
头衔=头衔;
等级=新字典();
foreach(学生中的var学生)
{
年级[学生]=0米;
}
}
公共字符串标题{get;}
公共IReadOnlyCollection学生{get=>grades.Keys.ToList();}
公共分数(字符串学生,小数点分数)
{
国际单项体育联合会(学生成绩)
{
这个。成绩[学生]=分数;
}
其他的
{
抛出新的ArgumentException(“未找到学生”,姓名(学生));
}
}
只读字典等级;
公共IREADONLYDICTIONAL Grades{get=>Grades;}
公共十进制平均分数{get=>Math.Round(grades.Values.Average(),1);}
#区域分级
//为等级值和字母值声明数组