简体   繁体   中英

String To Double Error With Switch-Case Calculator

Basically, the program calculates the two numbers we enter, according to the entered sign.

节目图片

But I got an error:

Cannot implicitly convert type 'string' to 'double'

To be honest I don't have any idea about this. I'm still learning the language. Need help about this.

Code:

private void button1_Click(object sender, EventArgs e)
{
    int num1, num2;
    string sembol;
    double rslt;
    num1 = Convert.ToInt32(textBox1.Text);
    num2 = Convert.ToInt32(textBox2.Text);
    sembol = textBox3.Text;
    rslt = textBox4.ToString();
    
    switch (sembol)
    {
        case "+": rslt = num1 + num2; break;
        case "-": rslt = num1 - num2; break;
        case "*": rslt = num1 * num2; break;
        case "/": rslt = num1 / num2; break;
    }
}

This row is causing the trouble:

rslt = textBox4.ToString();

You're trying to read an string containing object information into a double, that won't work.

Just skip this line. Then add this:

textBox4.Text = rslt.ToString();

to your code after the switch-Statement.

private void button1_Click(object sender, EventArgs e)
{
    int num1, num2;
    string sembol;
    double rslt;
    //num1 = Convert.ToInt32(textBox1.Text);
    //num2 = Convert.ToInt32(textBox2.Text);
    // This will try to read the input and make sure that no exception is thrown due to non numeric input
    if(!int.TryParse(textBox1.Text, out num1) || !int.TryParse(textBox2.Text, out num2))
    {
       textBox4.Text = "INVALID INPUT";
       return;
    }
    sembol = textBox3.Text;
    
    switch (sembol)
    {
        case "+": rslt = num1 + num2; break;
        case "-": rslt = num1 - num2; break;
        case "*": rslt = num1 * num2; break;
        case "/": rslt = num1 / num2; break;
        // This will handle anything that doesn't represent a valid operation
        default:
            textBox4.Text = "INVALID INPUT";
            return;
    }
    // Having checked every input for invalid characters, you can be sure rslt is properly set
    textBox4.Text = rslt.ToString();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM