我正在使用Windows Forms Application制作一个计算器,而且我现在很难过。 到目前为止,这是我的应用程序,它只能添加,但任何数量的数字。
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 Calculator
{
public partial class Form1 : Form
{
int num;
int answer = 0;
int i;
public Form1()
{
InitializeComponent();
}
private void plusButton_Click(object sender, EventArgs e)
{
answer += System.Convert.ToInt32(textBox1.Text);
ClearTextbox();
}
private void minusButton_Click(object sender, EventArgs e)
{
//answer -= System.Convert.ToInt32(textBox1.Text);
//ClearTextbox();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void divideButton_Click(object sender, EventArgs e)
{
}
private void multiplyButton_Click(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
num = 1;
displayInt(num);
}
private void button2_Click(object sender, EventArgs e)
{
num = 2;
displayInt(num);
}
private void button3_Click(object sender, EventArgs e)
{
num = 3;
displayInt(num);
}
private void button4_Click(object sender, EventArgs e)
{
num = 4;
displayInt(num);
}
private void button5_Click(object sender, EventArgs e)
{
num = 5;
displayInt(num);
}
private void button6_Click(object sender, EventArgs e)
{
num = 6;
displayInt(num);
}
private void button7_Click(object sender, EventArgs e)
{
num = 7;
displayInt(num);
}
private void button8_Click(object sender, EventArgs e)
{
num = 8;
displayInt(num);
}
private void button9_Click(object sender, EventArgs e)
{
num = 9;
displayInt(num);
}
private void button0_Click(object sender, EventArgs e)
{
num = 0;
displayInt(num);
}
private void resetButton_Click(object sender, EventArgs e)
{
ClearTextbox();
num = 0;
answer = 0;
}
public void displayInt(int num)
{
textBox1.Text = textBox1.Text + num.ToString();
}
public void ClearTextbox()
{
textBox1.Clear();
}
public void DisplayAnswer(int answer)
{
answer += System.Convert.ToInt32(textBox1.Text); //Answer = Answer + Textbox Stuff
textBox1.Clear();
textBox1.Text = answer.ToString();
}
private void equalsButton_Click(object sender, EventArgs e)
{
DisplayAnswer(answer);
num = 0;
answer = 0;
}
}
}
我不确定是否有办法等到按下另一个数字键,然后执行x + y。我听说过事件处理程序,但对我来说这是一个非常模糊的话题。
这是一张图片:http://img196.imageshack.us/img196/4127/12464e13e5154a949a9a457.png
*我希望它能够对超过2个数字进行操作。
谢谢!
答案 0 :(得分:2)
您的代码有点混乱,很难弄清楚您的意图。这段代码的帮助很快就会到来。我建议关注this simple calculator tutorial。它很好地解释了概念和步骤,包括按钮事件。
答案 1 :(得分:0)
你需要一个“+” - 按钮和一个“=” - 按钮。然后你的计算器有两个数字字段和两个状态:
1)输入第一个数字
2)输入第二个号码
你可以有一个变量,说明输入了哪个号码。
int field = 1;
按下数字按钮时,该数字必须附加到相应的字段。
按“+” - 按钮时,将状态改为
field = 2;
现在数字将被附加到第二个字段。
当您按下“=” - 按钮时,将两个现在仍然是字符串的数字转换为int
,添加它们并将它们输出到结果字段。将状态设置回
field = 1;
此外,“清除”按钮会清除字段并设置field = 1;
注意:正如Paul Sasik所说,你的代码有点乱。如果您为按钮提供了有意义的名称,例如btnDigit1
,btnDigit2
,btnPlus
,btnEquals
,btnClear
,我会帮忙。双击设计器中的按钮时,将创建btnPlus_Click
之类的事件处理程序。这比button17_Click
更清晰。