我正在使用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个数字进行操作 .
谢谢!
2 回答
你需要一个“”按钮和一个“=” - 按钮 . 然后你的计算器有两个数字字段和两个状态:
1)输入第一个数字
2)输入第二个数字
你可以有一个变量说明输入的是哪个号码 .
按下数字按钮时,该数字必须附加到相应的字段 .
当按下“”按钮将状态改为
现在,数字将附加到第二个字段 .
按"="按钮时,将两个数字(现在仍然是字符串)转换为
int
,添加它们并将它们输出到结果字段 . 将状态设置回另外"clear"按钮会清除字段并设置
field = 1;
注意:正如Paul Sasik所说,你的代码有点混乱 . 我会帮忙,如果你给你的按钮有意义的名字,如
btnDigit1
,btnDigit2
,btnPlus
,btnEquals
,btnClear
. 双击设计器中的按钮时,将创建btnPlus_Click
之类的事件处理程序 . 这比button17_Click
更清楚 .你的代码有点乱,很难弄清楚你的意图 . 对此代码的帮助将很快到来 . 我建议关注this simple calculator tutorial . 它很好地解释了概念和步骤,包括按钮事件 .