四则运算
一:题目
编写一个能对0--10之间的整数进行四则运算的“软件” 程序能接收用户输入的整数答案,并判断对错 程序结束时,统计出答对、答错的题目数量。
二:内容如下
1.先设置Form1窗体,向里面添加8个Lable控件,3个TextBox控件,2个Button控件,如图所示:
2:在Form2窗体中添加3个Lable控件,3个TextBox控件,如图所示:
3:添加好窗体后,设置各控件的属性
4:具体代码如下:
Form1:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace 计算
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public static int Count = 0; //题目总数
public static int right = 0; //正确的题目总数
private void button1_Click(object sender, EventArgs e)
{
RandomNum();
}
//自定义方法:产生1~10的随机数并在文本框中显示
private void RandomNum()
{
Random ran = new Random();
int n1, n2;
n1 = ran.Next(1, 11);
n2 = ran.Next(1, 11);
textBox1.Text = n1.ToString();
textBox2.Text = n2.ToString();
textBox3.Text = "";
Count++;
}
//当按下回车键表示输入结果
private void textBox3_KeyDown(object sender, KeyEventArgs e)
{
int Count;
string c = label9.Text;
switch (c)
{
case "+":
Count = int.Parse(textBox1.Text) + int.Parse(textBox2.Text);
break;
case "-":
Count = int.Parse(textBox1.Text) - int.Parse(textBox2.Text);
break;
case "x":
Count = int.Parse(textBox1.Text) * int.Parse(textBox2.Text);
break;
default:
Count = int.Parse(textBox1.Text) / int.Parse(textBox2.Text);
break
}
if (e.KeyCode == Keys.Enter)
{
if (textBox3.Text == Count.ToString())
right++;
RandomNum();
}
}
private void label5_Click(object sender, EventArgs e)
{
label10.Text = "+";
RandomNum();
}
private void label6_Click(object sender, EventArgs e)
{
label10.Text = "-";
RandomNum();
}
private void label7_Click(object sender, EventArgs e)
{
label10.Text = "*";
RandomNum();
}
private void label8_Click(object sender, EventArgs e)
{
label10.Text = "/";
RandomNum();
}
private void button2_Click_1(object sender, EventArgs e)
{
textBox3.Enabled = false;
Form2 frm2 = new Form2();
frm2.ShowDialog();
}
}
}
Form2:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace 计算
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
textBox1.Text = Form1.Count.ToString(); //题目总数
textBox2.Text = Form1.right.ToString(); //正确题目数
//正确率
textBox3.Text = ((Form1.right / (double)(Form1.Count)) * 100).ToString() + "%";
}
}
}
5:运行结果如下
三:总结
本来我以为打这个代码用不了多少时间,结果从查书,构思,代码。。。一共用了我三个多小时。还老是出现各种毛病,总感觉莫名其妙的,还是对各个代码具体是做什么的,有什么用,不够了解。通过这个代码,我以后一定要多多看书,这样在更改某个代码时更能清晰明了。再者,思路要清晰,明白具体流程,知道要做什么,先做什么,后做什么,这样才能更加节约时间。