使用C#怎么实现一个加减乘除计算器?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。
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, KeyPressEventArgs e) { OnlyEnterNumber(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不能为空!", "警告", MessageBoxButtons.OK, 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!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } result = inshu1 / inshu2; result = Round(result, 6); } txtResult.Text = Convert.ToString(result); } } }
看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。