本案例,采用VC6.0中的MFC模态对话框编写,该对话框可以实现加减乘除。
步骤如下:
一)创建一个模态对话框,具体请参考http://blog.csdn.net/sanqima/article/details/34076191
二)在对话框“四则运算”上,加上四个Button,依次命名为Add、sub、mul、div,例如,加法Add()的设置如下:
三)编写对应的响应函数Add()、Sub()、Mul()、Div(),代码如下:
void CTestDlg::OnAdd()
{
// TODO: Add your control notification handler code here
double num1,num2,num3;
char ch1[10],ch2[10],ch3[10];
GetDlgItem(IDC_EDIT1)->GetWindowText(ch1,10);
GetDlgItem(IDC_EDIT2)->GetWindowText(ch2,10);
num1=atof(ch1);
num2=atof(ch2);
num3=num1+num2;
gcvt(num3,10,ch3);
GetDlgItem(IDC_EDIT3)->SetWindowText(ch3);
}
void CTestDlg::OnSub()
{
// TODO: Add your control notification handler code here
double num1,num2,num3;
char ch1[10],ch2[10],ch3[10];
GetDlgItem(IDC_EDIT1)->GetWindowText(ch1,10);
GetDlgItem(IDC_EDIT2)->GetWindowText(ch2,10);
num1=atof(ch1);
num2=atof(ch2);
num3=num1-num2;
gcvt(num3,10,ch3);
GetDlgItem(IDC_EDIT3)->SetWindowText(ch3);
}
void CTestDlg::OnMul()
{
// TODO: Add your control notification handler code here
double num1,num2,num3;
char ch1[10],ch2[10],ch3[10];
GetDlgItem(IDC_EDIT1)->GetWindowText(ch1,10);
GetDlgItem(IDC_EDIT2)->GetWindowText(ch2,10);
num1=atof(ch1);
num2=atof(ch2);
num3=num1*num2;
gcvt(num3,10,ch3);
GetDlgItem(IDC_EDIT3)->SetWindowText(ch3);
}
void CTestDlg::OnDiv()
{
// TODO: Add your control notification handler code here
double num1,num2,num3;
char ch1[10],ch2[10],ch3[10];
GetDlgItem(IDC_EDIT1)->GetWindowText(ch1,10);
GetDlgItem(IDC_EDIT2)->GetWindowText(ch2,10);
num1=atof(ch1);
num2=atof(ch2);
if (num2==0)
{
MessageBox("除数不能为0,请从新输入!");
}else{
num3=num1/num2;
gcvt(num3,10,ch3);
GetDlgItem(IDC_EDIT3)->SetWindowText(ch3);
}
}
注意,double转为String时,使用atof(); String转为double时,使用gcvt(),引用的头文件为#include<stdlib.h>
double atof( const char *string );
char *gcvt(double value, int ndigit, char *buf);
value——被转换的值。 ndigit——存储的有效数字位数。 buf——结果的存储位置。
说明: gcvt函数把一个浮点值转换成一个字符串(包括一个小数点和可能的 符号字节)并存储该字符串在buffer中。该buffer应足够大以便容纳转换 的值加上结尾的空格字符,它是自动添加的。如果一个缓冲区的尺寸为 digits的尺寸+1,该函数覆盖该缓冲区的末尾。这是因为转换的字符串包 括一个小数点以及可能包含符号和指数信息。不提供上溢出。gcvt试图 以十进制格式产生digits数字,如果不可能,它以指数格式产生digits数字, 在转换时可能截除尾部的0。