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 WinFormsApp2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
double a = Convert.ToDouble(textBox1.Text);
double b = Convert.ToDouble(textBox3.Text);
string v = comboBox1.SelectedItem.ToString();
int x = 0;
int.TryParse(v, out x);
//x = Convert.ToInt32(v);异常
double sum = 0.0;
switch (x)
{
case '+':
sum = a + b;
break;
case '-':
sum = a - b;
break;
case '*':
sum = a * b;
break;
case '/':
if (b != 0)
{
sum = a / b;
}
break;
default:break;
}
//double sum = a + b;
textBox4.Text = sum.ToString();
}
public void My_Conbobox()
{
comboBox1.Items.Add("+");
comboBox1.Items.Add("-");
comboBox1.Items.Add("*");
comboBox1.Items.Add("/");
}
private void button2_Click(object sender, EventArgs e)
{
textBox1.Text = "";
textBox3.Text = "";
textBox4.Text = "";
/* Application.Exit();*/
}
private void Form1_Load(object sender, EventArgs e)
{
My_Conbobox();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
25行,你的字符串变量v是运算操作符,结果你想把它转成整型赋值给x?,那肯定直接返回false啊,所以x不会被赋值,switch里直接break了,所以sum维持了0
记得采纳
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 WinFormsApp2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
double a = Convert.ToDouble(textBox1.Text);
double b = Convert.ToDouble(textBox3.Text);
string v = comboBox1.SelectedItem.ToString();
char c = char.Parse(comboBox1.Text.Trim());
//x = Convert.ToInt32(v);异常
double sum = 0.0;
switch (c)
{
case '+':
sum = a + b;
break;
case '-':
sum = a - b;
break;
case '*':
sum = a * b;
break;
case '/':
if (b != 0)
{
sum = a / b;
}
break;
default:break;
}
//double sum = a + b;
textBox4.Text = sum.ToString();
}
public void My_Conbobox()
{
comboBox1.Items.Add("+");
comboBox1.Items.Add("-");
comboBox1.Items.Add("*");
comboBox1.Items.Add("/");
}
private void button2_Click(object sender, EventArgs e)
{
textBox1.Text = "";
textBox3.Text = "";
textBox4.Text = "";
/* Application.Exit();*/
}
private void Form1_Load(object sender, EventArgs e)
{
My_Conbobox();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}