通过VS编写C#实现10以内加减乘除运算及统计结果
文章目录
使用工具:Visual Studio 2022
提示:以下是本篇文章正文内容,下面案例可供参考
一、生成WindowsForm
(运行时)
(开始出题)
(答案错误)
添加label1,label2,label3,label4显示题目,Visible = false
添加TextBox输入答案,Visible = false
添加Button1和Button2,其中Button2(提交).Visible = false
添加ListBox记录结果
二、使用步骤
1.代码实现
代码如下(示例):
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 WindowsFormsApp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void label4_Click(object sender, EventArgs e)
{
}
int a,b;
int result;
string op;
Random rnd = new Random();
private void button2_Click(object sender, EventArgs e)
{
try
{
string str1 = textBox1.Text;
double d1 = double.Parse(str1);
}
catch
{
MessageBox.Show("未输入答案或输入答案格式错误!","Error");
listBox1.Items.Add(a+op+b+"="+textBox1.Text+ "\t ===>错误");
return;
}
string str = textBox1.Text;
double d = double.Parse(str);
string disp = ""+a +op+b+"="+str+" ";
if (d == result) {
disp += "☆";
}
else {
disp += "\t ===>错误";
}
listBox1.Items.Add(disp);
a = rnd.Next(9) + 1;
b = rnd.Next(9) + 1;
int c = rnd.Next(4);
switch (c)
{
case 0:
op = "+";
result = a + b;
break;
case 1:
op = "-";
result = a - b;
break;
case 2:
op = "*";
result = a * b;
break;
case 3:
op = "/";
result = a / b;
break;
}
label1.Text = a.ToString();
label2.Text = op;
label3.Text = b.ToString();
textBox1.Text = "";
}
private void button1_Click(object sender, EventArgs e)
{
a = rnd.Next(9) + 1;
b = rnd.Next(9) + 1;
int c = rnd.Next(4);
switch (c) {
case 0:
op = "+";
result = a + b;
break;
case 1:
op = "-";
result = a - b;
break;
case 2:
op = "*";
result = a * b;
break;
case 3:
op = "/";
result = a / b;
break;
}
label1.Text = a.ToString();
label2.Text = op;
label3.Text = b.ToString();
textBox1.Text = "";
button1.Visible = false;
button2.Visible = true;
label1.Visible = true;
label2.Visible = true;
label3.Visible = true;
label4.Visible = true;
textBox1.Visible = true;
button2.Location = button1.Location;
}
}
}
2.异常处理
代码如下(示例):
try
{
string str1 = textBox1.Text;
double d1 = double.Parse(str1);
}
catch
{
MessageBox.Show("未输入答案或输入答案格式错误!","Error");
listBox1.Items.Add(a+op+b+"="+textBox1.Text+ "\t ===>错误");
return;
}
该处使用的try-catch-finally负责对当TextBox内容为空时进行处理,当TextBox内容为空时,返回并进行提示,最后在ListBox中显示错误
总结
没有总结