计算器是简单的加减乘除运算。
主界面:
在点击按钮输入数字的时候,会出现在第三个文本框中显示第一个数字。
清除按钮就是清空文本框:
void CMyDlg::OnClear() { // TODO: Add your control notification handler code here UpdateData(TRUE); m_str1=""; m_fNumber1=0.0f; m_fNumber2=0.0f; m_iSign=0; m_RESULT=(int)""; m_str2=0; m_OPER=""; UpdateData(FALSE); }
点击 = 后,计算函数为:
void CMyDlg::OnButton16() { // TODO: Add your control notification handler code here //从edit获取数据进行计算,并将结果返回给edit4显示。 Calculator(); }
void CMyDlg::Calculator() { UpdateData(TRUE); m_fNumber2 = atof(m_str1);//字符到浮点型转换 m_RESULT = 0.0f;//结果是浮点型 switch (m_iSign)//根据符号来判断什么运算 { //加 case 0: m_RESULT = m_fNumber1 + m_fNumber2; break; //减 case 1: m_RESULT = m_fNumber1 - m_fNumber2; break; //乘 case 2: m_RESULT = m_fNumber1 * m_fNumber2; break; //除 case 3: if (m_fNumber2 == 0.0f) { m_RESULT = m_fNumber1;//非法运算 } else { m_RESULT = m_fNumber1 / m_fNumber2;//结果为浮点型,除法运算 } break; default: break; } m_fNumber1 = m_RESULT;//计算结果给 m_fNumber2 = 0.0f;//第二个数字置0(浮点型) UpdateData(FALSE); }
点击1后:
void CMyDlg::OnButton1() { // TODO: Add your control notification handler code here //edit显示1 UpdateData(TRUE); m_str1 =m_str1+ "1"; UpdateData(FALSE); }
上面直接用浮点型数据显示更好啊!(刚开始学的时候真是没有多尝试,没仔细看 控件变量的类型有 那么多!)
其他数字类似:
void CMyDlg::OnButton2() { // TODO: Add your control notification handler code here UpdateData(TRUE); m_str1 =m_str1+ "2"; UpdateData(FALSE); }
小数点:
void CMyDlg::OnButton15() { // TODO: Add your control notification handler code here //edit显示. UpdateData(TRUE); m_str1 =m_str1+ "."; UpdateData(FALSE); }
计算符号:
void CMyDlg::OnButton11() { // TODO: Add your control notification handler code here //edit显示+ UpdateData(TRUE); SaveValue1(); m_iSign = 0; m_OPER = m_OPER + "+"; UpdateData(FALSE); } void CMyDlg::OnButton12() { // TODO: Add your control notification handler code here //edit显示- UpdateData(TRUE); SaveValue1(); m_iSign = 1; m_OPER= m_OPER + "-"; UpdateData(FALSE); } void CMyDlg::OnButton13() { // TODO: Add your control notification handler code here //edit显示x UpdateData(TRUE); SaveValue1(); m_iSign = 2; m_OPER = m_OPER +"x"; UpdateData(FALSE); } void CMyDlg::OnButton14() { // TODO: Add your control notification handler code here //edit显示/ UpdateData(TRUE); SaveValue1(); m_iSign = 3; m_OPER= m_OPER + "/"; UpdateData(FALSE); }
头文件中:
int m_iSign; double m_fNumber2; double m_fNumber1; void SaveValue1(); void Calculator();