c++大作业:基于MFC的计算器实现(带文档)

更新:

最初的界面

更新后加入了计算sin,cos,tan,exp,log的结果

更新后的界面如下:

微软基础类库(英语:MicrosoftFoundation Classes,简称MFC)是微软公司提供的一个类库(class libraries),以C++类的形式封装了Windows API,并且包含一个应用程序框架,以减少应用程序开发人员的工作量。其中包含大量Windows句柄封装类和很多Windows的内建控件和组件的封装类。

实现的主要功能:通过输入数字,可以进行加减乘除、求根号、取模等计算,通过本代码可以扩展更多的功能。

用MFC实现的一个简单的计算器程序,其功能界面如下

部分代码如下

// CaculatorDlg.cpp : implementation file
//
 
#include "stdafx.h"
#include "Caculator.h"
#include "CaculatorDlg.h"
#include <string.h>
#include <math.h>
 
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
 
/
// CAboutDlg dialog used for App About
 
 
class CAboutDlg : public CDialog
{
public:
	CAboutDlg();
 
// Dialog Data
	//{{AFX_DATA(CAboutDlg)
	enum { IDD = IDD_ABOUTBOX };
	//}}AFX_DATA
 
	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(CAboutDlg)
	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
	//}}AFX_VIRTUAL
	
// Implementation
protected:
	//{{AFX_MSG(CAboutDlg)
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};
 
CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
	//{{AFX_DATA_INIT(CAboutDlg)
	//}}AFX_DATA_INIT
}
 
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CAboutDlg)
	//}}AFX_DATA_MAP
}
 
 
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
	//{{AFX_MSG_MAP(CAboutDlg)
		// No message handlers
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()
 
/
// CCaculatorDlg dialog
 
CCaculatorDlg::CCaculatorDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CCaculatorDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CCaculatorDlg)
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
 
void CCaculatorDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CCaculatorDlg)
	DDX_Control(pDX, IDC_BUTTON_AD, m_numad);
	DDX_Control(pDX, IDC_BUTTON_9, m_num9);
	DDX_Control(pDX, IDC_BUTTON_8, m_num8);
	DDX_Control(pDX, IDC_BUTTON_7, m_num7);
	DDX_Control(pDX, IDC_BUTTON_6, m_num6);
	DDX_Control(pDX, IDC_BUTTON_5, m_num5);
	DDX_Control(pDX, IDC_BUTTON_4, m_num4);
	DDX_Control(pDX, IDC_BUTTON_3, m_num3);
	DDX_Control(pDX, IDC_BUTTON_1, m_num1);
	DDX_Control(pDX, IDC_BUTTON_0, m_num0);
	DDX_Control(pDX, EDIT, m_edit);
	//}}AFX_DATA_MAP
}
 
BEGIN_MESSAGE_MAP(CCaculatorDlg, CDialog)
	//{{AFX_MSG_MAP(CCaculatorDlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_BUTTON_1, OnButton1)
	ON_BN_CLICKED(IDC_BUTTON_3, OnButton3)
	ON_BN_CLICKED(IDC_BUTTON_4, OnButton4)
	ON_BN_CLICKED(IDC_BUTTON_5, OnButton5)
	ON_BN_CLICKED(IDC_BUTTON_6, OnButton6)
	ON_BN_CLICKED(IDC_BUTTON_7, OnButton7)
	ON_BN_CLICKED(IDC_BUTTON_8, OnButton8)
	ON_BN_CLICKED(IDC_BUTTON_9, OnButton9)
	ON_BN_CLICKED(IDC_BUTTON_AD, OnButtonAd)
	ON_BN_CLICKED(IDC_BUTTON_C, OnButtonC)
	ON_BN_CLICKED(IDC_BUTTON_D, OnButtonD)
	ON_BN_CLICKED(IDC_BUTTON_DE, OnButtonDe)
	ON_BN_CLICKED(IDC_BUTTON_DI, OnButtonDi)
	ON_BN_CLICKED(IDC_BUTTON_EQ, OnButtonEq)
	ON_BN_CLICKED(IDC_BUTTON_MU, OnButtonMu)
	ON_BN_CLICKED(IDC_BUTTON_S, OnButtonS)
	ON_BN_CLICKED(IDC_BUTTON_Y, OnButtonY)
	ON_EN_UPDATE(EDIT, OnUpdateEDIT)
	ON_BN_CLICKED(IDC_BUTTON_0, OnButton0)
	ON_BN_CLICKED(IDC_BUTTON2, OnButton2)
	ON_BN_CLICKED(IDC_BUTTON_FU, OnButtonfu)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()
 
/
// CCaculatorDlg message handlers
 
BOOL CCaculatorDlg::OnInitDialog()
{
	CDialog::OnInitDialog();
 
	// Add "About..." menu item to system menu.
 
	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);
 
	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		CString strAboutMenu;
		strAboutMenu.LoadString(IDS_ABOUTBOX);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}
 
	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon
	
	// TODO: Add extra initialization here
	
	return TRUE;  // return TRUE  unless you set the focus to a control
}
 
void CCaculatorDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}
 
// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.
 
void CCaculatorDlg::OnPaint() 
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting
 
		SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);
 
		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;
 
		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}
 
// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CCaculatorDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}
 
int count=0;
char b[40];
char c=' ';
int fu=0;
int isd=0;
double sum=0;
int isDoublec=0;
void CCaculatorDlg::OnButton0() 
{
	// TODO: Add your control notification handler code here
    keyNum("0",'0');
 
}
 
void CCaculatorDlg::OnButton1() 
{
	// TODO: Add your control notification handler code here
    keyNum("1",'1');
	
}
 
void CCaculatorDlg::OnButton2() 
{
	// TODO: Add your control notification handler code here
    keyNum("2",'2');
}
 
void CCaculatorDlg::OnButton3() 
{
	// TODO: Add your control notification handler code here
	keyNum("3",'3');
}
 
void CCaculatorDlg::OnButton4() 
{
	// TODO: Add your control notification handler code here
	keyNum("4",'4');
 
}
 
void CCaculatorDlg::OnButton5() 
{
	// TODO: Add your control notification handler code here	
	keyNum("5",'5');
 
}
 
void CCaculatorDlg::OnButton6() 
{
	// TODO: Add your control notification handler code here
 
	keyNum("6",'6');
 
}
 
void CCaculatorDlg::OnButton7() 
{
	// TODO: Add your control notification handler code here
	keyNum("7",'7');
 
}
 
void CCaculatorDlg::OnButton8() 
{
	// TODO: Add your control notification handler code here
 
	keyNum("8",'8');
		
}
 
void CCaculatorDlg::OnButton9() 
{
	// TODO: Add your control notification handler code here
	keyNum("9",'9');
 
}
 
void CCaculatorDlg::OnButtonAd() 
{
	// TODO: Add your control notification handler code here
    handleResult('+');
}
 
void CCaculatorDlg::OnButtonC() 
{
	// TODO: Add your control notification handler code here
	m_edit.SetSel(0,-1);
	m_edit.ReplaceSel("0");
	int len=strlen(b);
	for(int i=0; i<len;i++)
	{
	 b[i]=NULL;
	}
	sum=0;
	count=0;
	fu=0;
	isd=0;
	isDoublec=0;	
}
 
void CCaculatorDlg::OnButtonD() 
{
	// TODO: Add your control notification handler code here
 
	m_edit.GetWindowText(b,20);
	int len=strlen(b);
	for(int i=0;i<len;i++)
		if(b[i]=='.')
			break;
	if(i==len)
	{
		b[len]='.';
		b[len+1]='\0';
	}
	m_edit.SetWindowText(b);
	isd=1;	
}
 
void CCaculatorDlg::OnButtonDe() 
{
	// TODO: Add your control notification handler code here
    handleResult('-');
}
 
void CCaculatorDlg::OnButtonDi() 
{
	// TODO: Add your control notification handler code here
    handleResult('/');
}
 
void CCaculatorDlg::OnButtonEq() 
{
	// TODO: Add your control notification handler code here
	isDoublec=0;
    handleResult(' ');
	count=0;
	sum=0;
	isDoublec=0;
}
 
void CCaculatorDlg::OnButtonMu() 
{
	// TODO: Add your control notification handler code here
    handleResult('*');
}
 
void CCaculatorDlg::OnButtonS() 
{
	// TODO: Add your control notification handler code here
 
	if(fu==1)
		return;
	isDoublec=0;
    handleResult(' ');
	count=0;
	sum=0;
	isDoublec=0;
	m_edit.GetWindowText(b,20);
	double n=atof(b);
	if(n >= 0)
	{
		n=sqrt(n);
	    CString szTemp;
        szTemp.Format(_T("%g"),n);
	    m_edit.SetWindowText(szTemp);
		count=0;
		isDoublec=0;	
	}
 
}
 
void CCaculatorDlg::OnButtonY() 
{
	// TODO: Add your control notification handler code here
    handleResult('%');	
}
 
void CCaculatorDlg::OnUpdateEDIT() 
{
	// TODO: If this is a RICHEDIT control, the control will not
	// send this notification unless you override the CDialog::OnInitDialog()
	// function to send the EM_SETEVENTMASK message to the control
	// with the ENM_UPDATE flag ORed into the lParam mask.
	
	// TODO: Add your control notification handler code here
//	char a[10];
//	scanf("%c",&a);
//	m_edit.SetWindowText(a);
	
}
 
 
void CCaculatorDlg::OnButtonfu() 
{
	// TODO: Add your control notification handler code here
	char isZero[20];
	m_edit.GetWindowText(isZero,20);
	if (atof(isZero) <0) 
	    fu=1;	
	if(fu==0 && isZero [0] != '0')
	{
		m_edit.GetWindowText(b,20);
		int len=strlen(b);
		for(int i=len;i>0;i--)
			b[i]=b[i-1];
		b[0]='-';
		b[len+1]='\0';
		m_edit.SetWindowText(b);
		fu=1;
	}	
	else if(fu==1)
	{
		m_edit.GetWindowText(b,20);
		int len=strlen(b);
		for(int i=0;i<len;i++)
			b[i]=b[i+1];
		m_edit.SetWindowText(b);
		fu=0;
	}	
}
 
BOOL CCaculatorDlg::PreTranslateMessage(MSG* pMsg) 
{
	// TODO: Add your specialized code here and/or call the base class
 
   if(pMsg->wParam == VK_RETURN)//当按下键为回车键时
    {
	    isDoublec=0;
        handleResult(' ');
	    count=0;
      	sum=0;
        return TRUE;
    }
    switch(LOWORD(pMsg->wParam)) 
		{
		    case '0':keyNum("0",'0');break;
			case '1':keyNum("1",'1');break;
			case '2':keyNum("2",'2');break;
			case '3':keyNum("3",'3');break;
			case '4':keyNum("4",'4');break;
			case '5':keyNum("5",'5');break;
			case '6':keyNum("6",'6');break;
			case '7':keyNum("7",'7');break;
			case '8':keyNum("8",'8');break;
			case '9':keyNum("9",'9');break;
 
		 	case '.':{	
						m_edit.GetWindowText(b,20);
						int len=strlen(b);
						for(int i=0;i<len;i++)
							if(b[i]=='.')
								break;
						if(i==len)
						{
							b[len]='.';
							b[len+1]='\0';
						}
						m_edit.SetWindowText(b);
						isd=1;	
						};break;
            case '+': handleResult('+');break;
            case '-': handleResult('-');break;
            case '*': handleResult('*');break;
            case '/': handleResult('/');break;
            //case '=': handleResult('=');break;
		} 
	
	return CDialog::PreTranslateMessage(pMsg);
}
void CCaculatorDlg::handleResult(char newc)
{
  if(isDoublec == 0)
  {
	m_edit.GetWindowText(b,20);
	if(c=='+')
		sum=sum+atof(b);
	else
		if(c=='-')
			sum=sum-atof(b);
		else
			if(c=='*')
				sum*=atof(b);
			else
				if(c=='/'&&atof(b)!=0)
					sum/=atof(b);
               else
					if( c=='/'&&atof(b)==0)
			         // 提示错误   
			         MessageBox("除数不能为零!");
					else
						if(c=='%' )
						{
 
						    if(isInt(sum) && isInt(atof(b)) && atof(b) != 0)
							{
								int yuNo= (int) sum;
								int y=(int) atof(b);
					    		yuNo %= y;
							    sum= (double) yuNo;
							}
							else
							  MessageBox("该数不能取余!");
 
						}
			    	      else
					         sum=atof(b);
	
	c=newc;
//	isDoublec=1;
	count=0;
	isd=0;
	CString szTemp;
    szTemp.Format(_T("%.12g"),sum);
	m_edit.SetWindowText(szTemp);
	}
	else if(isDoublec ==1)
	{
	  	c=newc;
		isDoublec =0;
	}
    isDoublec=1;
}
 
BOOL CCaculatorDlg::isInt(double a)
{
    const double eps = 1e-10;  // 精度范围
	if (a < 0)
	{
	    if (-a + (double)((int)a) < eps)
	    {
	    
		return true;							
	    }
	    else
	    return false;
    }
    else
	{
    if (a - (double)((int)a) < eps)
	{
	    
		return true;							
	}
	else
	    return false;
	}
}
 
void CCaculatorDlg::keyNum(char *no,char n)
{
 
	if(count==0 && isd == 0)
	{
	  m_edit.SetSel(0,-1);
	  m_edit.ReplaceSel(no);
 
	}
 
	else
	{
 
		m_edit.GetWindowText(b,20);
		int len=strlen(b);
		b[len]=n;
		b[len+1]='\0';
		m_edit.SetWindowText(b);
	}	
    if (n !='0')	
	    count=1;
	isDoublec = 0;
}

获取完整代码请查看全文

隐藏内容 需要支付:¥15

未经允许不得转载!c++大作业:基于MFC的计算器实现(带文档)