不是家庭作业..所以我有一个简单的控制台程序来读取考试成绩并打印出平均成绩和成绩。到目前为止,情况如下:
public static void Main ()
{
int sum = 0;
int count = 0;
double average = 0;
Console.WriteLine ("Enter all your exam scores one by one. When finished, enter -99");
string scores = Console.ReadLine ();
while (scores != "-99") {
sum += int.Parse (scores);
count++;
scores = Console.ReadLine ();
}
if (scores == "-99") {
average = sum / count;
if (average >= 90)
Console.WriteLine ("Your average score is {0}. This is good for a letter grade of A", average);
Console.WriteLine(....more scores etc...);
现在我想用 TryParse 检查无效条目。我想我会在另一个之前坚持另一个while循环并像这样改变原来的循环:
Console.WriteLine ("Enter all your exam scores one by one. When finished, enter -99");
string scores = Console.ReadLine ();
while (int.TryParse(scores, out numbers) == false){
Console.WriteLine("Please enter a valid integer")
scores = Console.ReadLine();
sum += int.Parse(scores);
count++;
}
while (scores != "-99" && int.TryParse(scores, out numbers) == true) {
sum += int.Parse (scores);
count++;
scores = Console.ReadLine ();
}
if (scores == "-99") {
average = sum / count;
if (average >= 90)
Console.WriteLine ("Your average score is {0}. This is good for a letter grade of A", average); ...etc...
这里的问题是,如果用户先输入有效条目,然后输入无效条目,则编译器无法返回第一个 while 循环来检查无效条目。所以我尝试交换 while 循环的位置。但这具有相同的效果;在输入无效条目后,它无法返回第一个 while 循环来检查有效条目。答案很可能很简单,但我被困住了。