C#实现简单加减乘除计算器
发布时间:2020-12-15 05:43:18 所属栏目:百科 来源:网络整理
导读:第一次学习C#,做了个简单的加减乘除计算器,只能实现两个因数的运算。 主要是练习下C#编程,和以前用过的VB差不多。与VB6不同的是,C#代码区分大小写。 Windows窗口程序主要也是由一些控件组成,响应响应的事件(event),实现具体的功能。 1.效果图如下所示
第一次学习C#,做了个简单的加减乘除计算器,只能实现两个因数的运算。 主要是练习下C#编程,和以前用过的VB差不多。与VB6不同的是,C#代码区分大小写。 Windows窗口程序主要也是由一些控件组成,响应响应的事件(event),实现具体的功能。 1.效果图如下所示 2.代码如下所示 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace WindowsApplication1 { public partial class Main : Form { public Main() { InitializeComponent(); } private void Main_Load(object sender,EventArgs e) { } private void txtInshu1_TextChanged(object sender,EventArgs e) { } private void txtInshu1_KeyPress(object sender,KeyPressEventArgs e) { OnlyEnterNumber(sender,e); } //// <summary> /// 只能输入数字(含负号小数点) /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public static void OnlyEnterNumber(object sender,KeyPressEventArgs e) { if ((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8 && e.KeyChar != 13 && e.KeyChar != 45 && e.KeyChar != 46) { e.Handled = true; } // 输入为负号时,只能输入一次且只能输入一次 if (e.KeyChar == 45 && (((TextBox)sender).SelectionStart != 0 || ((TextBox)sender).Text.IndexOf("-") >= 0)) e.Handled = true; if (e.KeyChar == 46 && ((TextBox)sender).Text.IndexOf(".") >= 0) e.Handled = true; } /* * 参数:d表示要四舍五入的数;i表示要保留的小数点后位数。 * 正负数都四舍五入,适合数据统计的显示 */ double Round(double d,int i) { if (d >= 0) { d += 5 * Math.Pow(10,-(i + 1)); } else { d += -5 * Math.Pow(10,-(i + 1)); } string str = d.ToString(); string[] strs = str.Split('.'); int idot = str.IndexOf('.'); string prestr = strs[0]; string poststr = strs[1]; if (poststr.Length > i) { poststr = str.Substring(idot + 1,i); } string strd = prestr + "." + poststr; d = Double.Parse(strd); return d; } private void txtInshu2_TextChanged(object sender,EventArgs e) { } private void txtInshu2_KeyPress_1(object sender,e); } private void btnJisuan_Click(object sender,EventArgs e) { if (txtInshu1.Text == "") { MessageBox.Show("因数1不能为空!","警告",MessageBoxButtons.OK,MessageBoxIcon.Warning); return; } if (txtInshu2.Text == "") { MessageBox.Show("因数2不能为空!",MessageBoxIcon.Warning); return; } double inshu1 = Convert.ToDouble(txtInshu1.Text); double inshu2 = Convert.ToDouble(txtInshu2.Text); double result = 0.0; if (radioBtnJia.Checked) { result = inshu1 + inshu2; } if (radioBtnJian.Checked) { result = inshu1 - inshu2; } if (radioBtnCheng.Checked) { result = inshu1 * inshu2; } if (radioBtnChu.Checked) { if (0 == inshu2) { MessageBox.Show("因数2做除数不能为0!",MessageBoxIcon.Warning); return; } result = inshu1 / inshu2; result = Round(result,6); } txtResult.Text = Convert.ToString(result); } } } 因数输入框只允许输入数字和小数点负号的代码是从网络上引用的。 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。 您可能感兴趣的文章:
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |