【发布时间】:2018-01-23 17:40:21
【问题描述】:
我是 C# 新手,正在尝试使用哨兵控制循环创建 GPA 计算器。要结束循环,我希望用户输入一个“x”,但它会引发异常。我很确定这是因为 'x' 不是双精度类型,但我不确定如何使它工作。我之前使用一个数字退出,但它一直被添加到gradeTotal。任何建议都会很棒!谢谢!
代码:
class Program
{
static void Main(string[] args)
{
double gradeTotal = 0;
int[] score = new int[100];
string inValue;
int scoreCnt = 0;
Console.WriteLine("When entering grades, use a 0-4 scale. Remember;
A = 4, B = 3, C = 2, D = 1, F = 0");
Console.WriteLine("Enter grade {0}: ((X to exit)) ", scoreCnt + 1);
inValue = Console.ReadLine();
gradeTotal += double.Parse(inValue);//This may be a problem area
while (inValue != "x")
{
if (int.TryParse(inValue, out score[scoreCnt]) == false)
Console.WriteLine("Invalid data -" + "0 stored in array");
++scoreCnt;
Console.WriteLine("Enter Score{0}: ((X to exit)) ", scoreCnt +
1);
inValue = Console.ReadLine();
gradeTotal += double.Parse(inValue);//This is a problem area
}
Console.WriteLine("The number of scores: " + scoreCnt);
Console.WriteLine("Your GPA is: " + gradeTotal);//Obviously not the
//right calculation, just trying to figure it out
Console.ReadLine();
}
}
【问题讨论】:
-
你遇到了什么异常?
-
如果按下任何非数字键就会发生这种情况。改用Int.TryParse(),它会告诉你它是否是一个有效的整数。 (不需要双精度,因为您只需要 0 到 4)
-
请从搜索结果中选择您选择的副本 - bing.com/search?q=c%23+formatexception+double
-
即使我使用 int.TryParse() 我得到“在 mscorlib.dll 中发生类型为 'System.FormatException' 的未处理异常附加信息:输入字符串的格式不正确。”跨度>
标签: c#