2 fanage fanage 于 2016.03.27 18:05 提问

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;
    }
}

}

3个回答

caozhy
caozhy   Ds   Rxr 2016.03.27 18:06

txtAnswer.Text;里面的内容不是一个合法的浮点数,比如说有多余的空格,数字和符号是全角字符,或者它根本为空。

herozhangbz
herozhangbz   2016.03.28 09:00

你打个断点跟一下代码,看看那个str是什么。你可以用tryparse判断一下能不能转换。if(double.tryparse(str))然后再操作

u011375896
u011375896   2016.03.28 21:00

我去,你牛,parse竟然不判断一下就用,try{}catch{}

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!