用模态对话框实现加减乘除

本案例,採用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。

完整代码地址:http://download.csdn.net/detail/sanqima/7546847

原文地址:https://www.cnblogs.com/yutingliuyl/p/6717825.html