问题描述
- C#运行时出现错误,求大神指点
-
“System.FormatException”类型的未经处理的异常在 mscorlib.dll 中发生其他信息: 输入字符串的格式不正确。
为什么doubleparse那里错了?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;namespace 算数练习
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}int a, b; int x,y; string op; int result; Random rnd = new Random(); private void Form1_Load(object sender, EventArgs e) { } private void lalresult_Click(object sender, EventArgs e) { } private void lalA_Click(object sender, EventArgs e) { } private void rabtn100add_CheckedChanged(object sender, EventArgs e) { x = 99; y = 2; } private void rabtn10mul_CheckedChanged(object sender, EventArgs e) { x = 9; y = 4; } private void timexchange_Tick(object sender, EventArgs e) { a = rnd.Next(x) + 1; b = rnd.Next(x) + 1; int c = rnd.Next(y); switch (c) { case 0: op = "+"; result = a + b; break; case 1: op = "-"; result = a - b; break; case 2: op = "*"; result = a * b; break; case 3: op = "/"; result = a / b; break; } lalA.Text = a.ToString(); lalop.Text = op; lalB.Text = b.ToString(); txtAnswer.Text = ""; string str = txtAnswer.Text; double d = double.Parse(str);//这里错了,怎么改? string disp = "" + a + op + b + "=" + str + " "; if (d == result) disp += "√"; else disp += "×"; listBox1.Items.Add(disp); } private void btnfast_Click(object sender, EventArgs e) { timexchange.Interval -= 500; } private void listBox1_SelectedIndexChanged(object sender, EventArgs e) { string str = txtAnswer.Text; double d = double.Parse(str); string disp = "" + a + op + b + "=" + str + " "; if (d == result) disp += "√"; else disp += "×"; listBox1.Items.Add(disp); } private void btnslow_Click(object sender, EventArgs e) { timexchange.Interval += 500; } private void rabtn10add_CheckedChanged(object sender, EventArgs e) { x = 9; y = 2; } }
}
解决方案
txtAnswer.Text;里面的内容不是一个合法的浮点数,比如说有多余的空格,数字和符号是全角字符,或者它根本为空。
解决方案二:
你打个断点跟一下代码,看看那个str是什么。你可以用tryparse判断一下能不能转换。if(double.tryparse(str))然后再操作
解决方案三:
我去,你牛,parse竟然不判断一下就用,try{}catch{}
时间: 2024-10-07 08:50:47