输入的字符串格式不正确,为double.Parse [英] Input string was not in a correct format in double.Parse

查看:344
本文介绍了输入的字符串格式不正确,为double.Parse的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C#的新手。我正在尝试制作一个计算器,但是发生以下错误:

I am new to C#. I'm trying to make a calculator, but the following error occurred:


输入字符串的格式不正确。

Input string was not in a correct format.

这是代码的摘要:

double num1, num2, result;

private void button14_Click(object sender, EventArgs e)
{
    num1 = Convert.ToDouble(textBox1.Text);
    textBox1.Text = String.Empty;
    num2 = double.Parse(textBox1.Text);   **//ERROR OCCURED HERE**
    result = num1 - num2;
}

private void button13_Click(object sender, EventArgs e)
{
    num1 = Convert.ToDouble(textBox1.Text);
    textBox1.Text = String.Empty;
    num2 = System.Double.Parse(textBox1.Text);  **//ERROR OCCURED HERE**
    result = num1 + num2;
}

如何将字符串转换为双精度类型?

How to convert string to a double type?

推荐答案

您尝试使用此代码实现什么?

What are you trying to achieve with this code? It seems that your algorythm is wrong.

就像其他人所说的那样,这段代码

Like others said, this code

textBox1.Text = String.Empty;
num2 = double.Parse(textBox1.Text);

将引发异常,因为无法将空字符串转换为Double!

will throw an Exception because an empty string cannot be converted to Double!

所以,我想知道为什么您要重置字段。我考虑了一会儿,也许我明白了您要做什么。假设您在TextBox1中输入数字。然后,按-按钮进行减法,然后要输入第二个数字以查看结果。是这样吗如果是这样,您编写的代码将不会等待下一次输入!

So, I'm wondering why did you reset your field. I thought about it for a while, and maybe I got what are you trying to do. Let's say you type a number in TextBox1. Then you press the "-" button to subtract and then you want to enter the second number to view the result. Is this the case? If it is, the code you wrote is not going to wait for your next input!

实际上,当您单击按钮时,它只会执行您编写的所有行。我会写这样的东西。

In fact, when you click the button, it just executes all the lines you wrote. I'd write something like this instead.

double num1, num2, result;
string operation;

private void button14_Click(object sender, EventArgs e) //Minus Button
{
    if (textBox1.Text != String.Empty) //Added if statement to see if the textBox is empty
        num1 = Convert.ToDouble(textBox1.Text);
    else
        num1 = 0; //If textBox is empty, set num1 to 0
    textBox1.Text = String.Empty;
    operation = "-";
}

private void button13_Click(object sender, EventArgs e) //Equals Button
{
    if (textBox1.Text != String.Empty)
        num2 = Convert.ToDouble(textBox1.Text);
    else
        num2 = 0;
    if (operation == "-")
    {
        result = num1 - num2;
        textBox1.Text = Convert.ToString(result);
    }
    if (operation == "+")
    {
        //You got it
    }
    //And so on...
}

编辑:如果字符串为空,则将始终抛出异常,因此我添加了一个控件。如果字符串为空,则值变为零。

If the string is empty, this is going to always throw Exceptions, so I added a control. If the string is empty, value becomes zero.

这篇关于输入的字符串格式不正确,为double.Parse的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆