C# 多行计算
本文关键字:计算 | 更新日期: 2023-09-27 18:33:10
我现在开始学习C#。我在处理讲师要求我做的问题时遇到了问题。下面是图形用户界面。
http://i.share.pho.to/daa36a24_c.png
这是我做的代码,但我没有设法编写下面提到的代码部分
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
double num1;
double num2;
double answer;
num1 = double.Parse(textBox1.Text);
num2 = double.Parse(textBox2.Text);
textBox4.Text = Convert.ToString(answer);
}
}
}
我需要加/减/乘/除第一个和第二个数字,以便它产生 -->(第一个数字 + 运算 + 第二个数字 = 答案)。
问题是我需要通过单击文本框上的 +、-、* 、/符号来选择操作。我可以通过使用单选按钮等轻松做到这一点,但我的讲师坚持这种格式。请协助"操作"选择的编码。谢谢。
只要操作在列表框中,请使用以下命令:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
double num1;
double num2;
double answer;
num1 = double.Parse(textBox1.Text);
num2 = double.Parse(textBox2.Text);
if (listBox1.SelectedIndex == 0)
{
answer = num1 + num2
}
if (listBox1.SelectedIndex == 1)
{
answer = num1 - num2
}
if (listBox1.SelectedIndex == 2)
{
answer = num1 * num2
}
if (listBox1.SelectedIndex == 3)
{
answer = num1 / num2
}
textBox4.Text = Convert.ToString(answer);
}
}
}
您可以使用列表框的OnIndexChanged
事件来了解选择了哪个运算符。
这将允许您在每次单击列表框时进行计算。
请注意,在 operatorListBox1_SelectedIndexChanged
事件方法中,使用 sender
(单击的对象)来查找SelectedItem
。 将其转换为字符串(它在列表框中的对象),您的符号将出现。(无双关语)
using System;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private int firstNum = 2;
private int secondNum = 4;
private int answer;
public Form2()
{
InitializeComponent();
operatorListBox1.Items.Add("+");
operatorListBox1.Items.Add("-");
operatorListBox1.Items.Add("*");
operatorListBox1.Items.Add("/");
//this next line would go in your designer.cs file. I put it here for completeness
this.operatorListBox1.SelectedIndexChanged += new System.EventHandler(this.operatorListBox1_SelectedIndexChanged);
}
private void operatorListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
calculateAnswer(((ListBox)sender).SelectedItem.ToString());
}
private void calculateAnswer(string sign)
{
switch (sign)
{
case "+":
answer = firstNum + secondNum;
break;
case "-":
answer = firstNum - secondNum;
break;
case "*":
answer = firstNum * secondNum;
break;
case "/":
answer = firstNum / secondNum;
break;
}
textBox4.Text = firstNum + " " + sign + " " + secondNum + " = " + answer;
}
}
}