计算器VC源代码
C语言实现计算器功能

C语言实现计算器功能C语言计算器实现是一种基本的编程练习,可以结合简单的数学表达式解析和计算功能来实现一个基本的计算器。
以下是一个简单的示例,它可以接受用户输入的数学表达式并返回计算结果。
首先,我们需要包含标准输入/输出库(stdio.h)和字符串处理库(string.h)。
我们还需要定义一些函数来处理数学表达式的解析和计算。
```c#include <stdio.h>#include <string.h>//返回运算符的优先级int precedence(char op)if (op == '+' , op == '-')return 1;if (op == '*' , op == '/')return 2;return 0;//执行四则运算int calculate(int a, int b, char op)switch (op)case '+':return a + b;case '-':return a - b;case '*':return a * b;case '/':return a / b;}return 0;//解析数学表达式并计算结果int evaluate(char *expression)int i;//创建两个空栈,用于操作数和运算符int values[100];int top_values = -1;char ops[100];int top_ops = -1;//遍历表达式的每个字符for (i = 0; i < strlen(expression); i++)//如果字符是一个数字,将其解析为整数,并将其推到操作数栈中if (expression[i] >= '0' && expression[i] <= '9')int value = 0;while (i < strlen(expression) && expression[i] >= '0' && expression[i] <= '9')value = value * 10 + (expression[i] - '0');i++;}values[++top_values] = value;}//如果字符是一个左括号,将其推到运算符栈中else if (expression[i] == '(')ops[++top_ops] = expression[i];}//如果字符是一个右括号,执行所有高优先级的运算else if (expression[i] == ')')while (top_ops > -1 && ops[top_ops] != '(')int b = values[top_values--];int a = values[top_values--];char op = ops[top_ops--];values[++top_values] = calculate(a, b, op);}top_ops--;}//如果字符是一个运算符,执行所有高优先级的运算elsewhile (top_ops > -1 && precedence(ops[top_ops]) >= precedence(expression[i]))int b = values[top_values--];int a = values[top_values--];char op = ops[top_ops--];values[++top_values] = calculate(a, b, op);}ops[++top_ops] = expression[i];}}//执行剩余的运算while (top_ops > -1)int b = values[top_values--];int a = values[top_values--];char op = ops[top_ops--];values[++top_values] = calculate(a, b, op);}//返回最终结果return values[top_values];int mainchar expression[100];printf("请输入数学表达式:");scanf("%s", expression);int result = evaluate(expression);printf("结果:%d\n", result);return 0;```上面的代码使用了栈来解析和计算数学表达式。
简单计算器c语言源码

#include <stdio.h>#include <string.h>#include <ctype.h>#include <math.h>//expression evaluate#define iMUL 0#define iDIV 1#define iADD 2#define iSUB 3#define iCap 4//#define LtKH 5//#define RtKH 6#define MaxSize 100void iPush(float);float iPop();float StaOperand[MaxSize];int iTop=-1;//char Srcexp[MaxSize];char Capaexp[MaxSize];char RevPolishexp[MaxSize];float NumCapaTab[26];char validexp[]="*/+-()";char NumSets[]="0123456789";char StackSymb[MaxSize];int operands;//void NumsToCapas(char [], int , char [], float []);int CheckExpress(char);int PriorChar(char,char);int GetOperator(char [], char);void counterPolishexp(char INexp[], int slen, char Outexp[]); float CalcRevPolishexp(char [], float [], char [], int);void main(){char ch;char s;int bl=1;while(bl==1){int ilen;float iResult=0.0;printf("输入计算表达式(最后以=号结束):\n");memset(StackSymb,0,MaxSize);memset(NumCapaTab,0,26); //A--NO.1, B--NO.2, etc.gets(Srcexp);ilen=strlen(Srcexp);NumsToCapas(Srcexp,ilen,Capaexp,NumCapaTab);ilen=strlen(Capaexp);counterPolishexp(Capaexp,ilen,RevPolishexp);ilen=strlen(RevPolishexp);iResult=CalcRevPolishexp(validexp, NumCapaTab, RevPolishexp,ilen);printf("\n计算结果:\n%.6f\n",iResult);printf("是否继续运算?(Y/N)\n");ch=getchar();s=getchar();//接受回车if(ch=='y'||ch=='Y'){bl=1;}else{bl=0;}}}void iPush(float value){if(iTop<MaxSize) StaOperand[++iTop]=value;}float iPop(){if(iTop>-1)return StaOperand[iTop--];return -1.0;}void NumsToCapas(char Srcexp[], int slen, char Capaexp[], float NumCapaTab[]) {char ch;int i, j, k, flg=0;int sign;float val=0.0,power=10.0;i=0; j=0; k=0;while (i<slen){ch=Srcexp[i];if (i==0){sign=(ch=='-')?-1:1;if(ch=='+'||ch=='-'){ch=Srcexp[++i];flg=1;}}if (isdigit(ch)){val=ch-'0';while (isdigit(ch=Srcexp[++i])) {val=val*10.0+ch-'0';}if (ch=='.'){while(isdigit(ch=Srcexp[++i])) {val=val+(ch-'0')/power; power*=10;}} //end ifif(flg){val*=sign;flg=0;}} //end if//write Capaexp array// write NO.j to arrayif(val){Capaexp[k++]='A'+j; Capaexp[k++]=ch;NumCapaTab[j++]=val; //A--0, B--1,and C, etc.}else{Capaexp[k++]=ch;}val=0.0;power=10.0;//i++;}Capaexp[k]='\0';operands=j;}float CalcRevPolishexp(char validexp[], float NumCapaTab[], char RevPolishexp[], int slen) {float sval=0.0, op1,op2;int i, rt;char ch;//recursive stacki=0;while((ch=RevPolishexp[i]) && i<slen){switch(rt=GetOperator(validexp, ch)){case iMUL: op2=iPop(); op1=iPop();sval=op1*op2;iPush(sval);break;case iDIV: op2=iPop(); op1=iPop();if(!fabs(op2)){printf("overflow\n");iPush(0);break;}sval=op1/op2;iPush(sval);break;case iADD: op2=iPop(); op1=iPop();sval=op1+op2;iPush(sval);break;case iSUB: op2=iPop(); op1=iPop();sval=op1-op2;iPush(sval);break;case iCap: iPush(NumCapaTab[ch-'A']); break;default: ;}++i;}while(iTop>-1){sval=iPop();}return sval;}int GetOperator(char validexp[],char oper) {int oplen,i=0;oplen=strlen(validexp);if (!oplen) return -1;if(isalpha(oper)) return 4;while(i<oplen && validexp[i]!=oper) ++i;if(i==oplen || i>=4) return -1;return i;}int CheckExpress(char ch){int i=0;char cc;while((cc=validexp[i]) && ch!=cc) ++i;if (!cc)return 0;return 1;}int PriorChar(char curch, char stach){//栈外优先级高于(>)栈顶优先级时,才入栈//否则(<=),一律出栈if (curch==stach) return 0; //等于时应该出栈else if (curch=='*' || curch=='/'){if(stach!='*' && stach!='/')return 1;}else if (curch=='+' || curch=='-'){if (stach=='(' || stach==')')return 1;}else if (curch=='('){if (stach==')')return 1;}return 0;}void counterPolishexp(char INexp[], int slen, char Outexp[]) {int i, j, k,pr;char t;i=0;j=k=0;while (INexp[i]!='=' && i<slen){if (INexp[i]=='(')StackSymb[k++]=INexp[i];//iPush(*(INexp+i));else if(INexp[i]==')'){//if((t=iPop())!=-1)while((t=StackSymb[k-1])!='('){Outexp[j++]=t;k--;}k--;}else if (CheckExpress(INexp[i])) // is oparator{// printf("operator %c k=%d\n",INexp[i],k);while (k){// iPush(*(INexp+i));if(pr=PriorChar(INexp[i],StackSymb[k-1])) break;else{//if ((t=iPop())!=-1)t=StackSymb[k-1]; k--;Outexp[j++]=t;}} //end whileStackSymb[k++]=INexp[i]; //common process }else //if() 变量名{// printf("operand %c k=%d\n",INexp[i],k); Outexp[j++]=INexp[i];}i++; //}while (k){t=StackSymb[k-1]; k--;Outexp[j++]=t;}Outexp[j]='\0';}。
C语言计算器源代码

C语言计算器源代码下面是一个简单的C语言计算器源代码:```c#include<stdio.h>int mainfloat num1, num2, result;char operator;printf("请输入两个数字:");scanf("%f %f", &num1, &num2);printf("请选择运算符(+,-,*,/):"); scanf(" %c", &operator);switch(operator)case '+':result = num1 + num2;printf("结果: %.2f\n", result);break;case '-':result = num1 - num2;printf("结果: %.2f\n", result);break;case '*':result = num1 * num2;printf("结果: %.2f\n", result); break;case '/':if(num2 != 0)result = num1 / num2;printf("结果: %.2f\n", result); }elseprintf("除数不能为0!\n");}break;default:printf("无效的运算符!\n"); break;}return 0;```这个计算器程序可以接受两个数字和一个运算符作为输入,并根据运算符的类型进行相应的计算。
程序使用了`switch`语句来根据不同的运算符执行不同的操作。
输入数字之后,输出计算结果或者错误提示信息。
VC++编写计算器

VC++写的计算器程序源代码课设了,用vc++写了一个计算器小程序,一个系差不多都用的我的代码,最高兴的是自己可以想到用bool变量来区分整数和小数,还有就是在连续运算的时候我没有用大家都用的复制代码的方法,而是用数组实现了。
有点小兴奋,把代码贴上来,呵呵,望大家多多提意见……严格意义上说这是我的第一个像样的MFC小程序。
(对话框控件变量,消息处理函数的关联以及变量的声明和初始化省略)// jisuanqiDlg.cpp : implementation file//#include "stdafx.h"#include "jisuanqi.h"#include "jisuanqiDlg.h"#include "math.h"#ifdef _DEBUG#define new DEBUG_NEW#undef THIS_FILEstatic char THIS_FILE[] = __FILE__;#endif///////////////////////////////////////////////////////////////////////////// // CAboutDlg dialog used for App Aboutclass 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// Implementationprotected://{{AFX_MSG(CAboutDlg)//}}AFX_MSGDECLARE_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_MAPEND_MESSAGE_MAP()///////////////////////////////////////////////////////////////////////////// // CJisuanqiDlg dialogCJisuanqiDlg::CJisuanqiDlg(CWnd* pParent ): CDialog(CJisuanqiDlg::IDD, pParent){//{{AFX_DATA_INIT(CJisuanqiDlg)m_num = 0.0;//}}AFX_DATA_INIT// Note that LoadIcon does not require a subsequent DestroyIcon in Win32m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);}void CJisuanqiDlg::DoDataExchange(CDataExchange* pDX){CDialog::DoDataExchange(pDX);//{{AFX_DATA_MAP(CJisuanqiDlg)DDX_Text(pDX, IDC_EDIT1, m_num);//}}AFX_DATA_MAP}BEGIN_MESSAGE_MAP(CJisuanqiDlg, CDialog)//{{AFX_MSG_MAP(CJisuanqiDlg)ON_WM_SYSCOMMAND()ON_WM_PAINT()ON_WM_QUERYDRAGICON()ON_BN_CLICKED(IDC_BUTTON1, OnButton1)ON_BN_CLICKED(IDC_BUTTON2, OnButton2)ON_BN_CLICKED(IDC_BUTTON3, OnButton3)ON_BN_CLICKED(IDC_BUTTON4, OnButton4)ON_BN_CLICKED(IDC_BUTTON5, OnButton5)ON_BN_CLICKED(IDC_BUTTON6, OnButton6)ON_BN_CLICKED(IDC_BUTTON7, OnButton7)ON_BN_CLICKED(IDC_BUTTON8, OnButton8)ON_BN_CLICKED(IDC_BUTTON9, OnButton9)ON_BN_CLICKED(IDC_BUTTON14, OnButton0)ON_BN_CLICKED(IDC_BUTTON15, OnButtonPoint)ON_BN_CLICKED(IDC_BUTTON16, OnButtonEqual)ON_BN_CLICKED(IDC_BUTTON13, OnButtonChu)ON_BN_CLICKED(IDC_BUTTON12, OnButtonMul)ON_BN_CLICKED(IDC_BUTTON11, OnButtonSub)ON_BN_CLICKED(IDC_BUTTON10, OnButtonAdd)ON_BN_CLICKED(IDC_BUTTON17, OnButtondelet)ON_BN_CLICKED(IDC_BUTTON18, OnButtonclear)ON_BN_CLICKED(IDC_BUTTON19, OnButtonkaifang)ON_BN_CLICKED(IDC_BUTTON20, OnButtonziranduishu)ON_BN_CLICKED(IDC_BUTTON21, OnButtonchangyongduishu)//}}AFX_MSG_MAPEND_MESSAGE_MAP()///////////////////////////////////////////////////////////////////////////// // CJisuanqiDlg message handlersBOOL CJisuanqiDlg::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 dialogSetIcon(m_hIcon, TRUE); // Set big iconSetIcon(m_hIcon, FALSE); // Set small icon// TODO: Add extra initialization heret=true;j=true;i=10;p=0;q=0;m_num=0;m_lnum=0;return TRUE; // return TRUE unless you set the focus to a control}void CJisuanqiDlg::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 CJisuanqiDlg::OnPaint(){if (IsIconic()){CPaintDC dc(this); // device context for paintingSendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);// Center icon in client rectangleint 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 icondc.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 CJisuanqiDlg::OnQueryDragIcon(){return (HCURSOR) m_hIcon;}void CJisuanqiDlg::OnButton1(){// TODO: Add your control notification handler code hereif(t){m_num=m_num*10+1;UpdateData(FALSE);}else{m_num=m_num+1.0/i;i*=10;UpdateData(FALSE);}}void CJisuanqiDlg::OnButton2(){// TODO: Add your control notification handler code hereif(t){m_num=m_num*10+2;UpdateData(FALSE);else{m_num=m_num+2.0/i;i*=10;UpdateData(FALSE);}}void CJisuanqiDlg::OnButton3(){// TODO: Add your control notification handler code hereif(t){m_num=m_num*10+3;UpdateData(FALSE);}else{m_num=m_num+3.0/i;i*=10;UpdateData(FALSE);}}void CJisuanqiDlg::OnButton4(){// TODO: Add your control notification handler code hereif(t){m_num=m_num*10+4;UpdateData(FALSE);else{m_num=m_num+4.0/i;i*=10;UpdateData(FALSE);}}void CJisuanqiDlg::OnButton5(){// TODO: Add your control notification handler code hereif(t){m_num=m_num*10+5;UpdateData(FALSE);}else{m_num=m_num+5.0/i;i*=10;UpdateData(FALSE);}}void CJisuanqiDlg::OnButton6(){// TODO: Add your control notification handler code hereif(t){m_num=m_num*10+6;UpdateData(FALSE);else{m_num=m_num+6.0/i;i*=10;UpdateData(FALSE);}}void CJisuanqiDlg::OnButton7(){// TODO: Add your control notification handler code hereif(t){m_num=m_num*10+7;UpdateData(FALSE);}else{m_num=m_num+7.0/i;i*=10;UpdateData(FALSE);}}void CJisuanqiDlg::OnButton8(){// TODO: Add your control notification handler code hereif(t){m_num=m_num*10+8;UpdateData(FALSE);else{m_num=m_num+8.0/i;i*=10;UpdateData(FALSE);}}void CJisuanqiDlg::OnButton9(){// TODO: Add your control notification handler code hereif(t){m_num=m_num*10+9;UpdateData(FALSE);}else{m_num=m_num+9.0/i;i*=10;UpdateData(FALSE);}}void CJisuanqiDlg::OnButton0(){// TODO: Add your control notification handler code here //UpdateData();if(t){m_num=m_num*10+0;UpdateData(FALSE);}else{m_num=m_num+0.0/i;i*=10;UpdateData(FALSE);}}void CJisuanqiDlg::OnButtonPoint(){// TODO: Add your control notification handler code here int i=10;t=false;}void CJisuanqiDlg::OnButtonEqual(){// TODO: Add your control notification handler code hereswitch(r){case '+':{m_num=m_num+m_lnum;UpdateData(FALSE);break;}case '-':{m_num=m_snum-m_num;UpdateData(FALSE);break;}case '*':{m_num=m_mnum*m_num;UpdateData(FALSE);break;}case '/':{if(m_num==0){MessageBox("除数不能是0!");}else{m_num=m_cnum/m_num;UpdateData(FALSE);break;}}}t=true;}void CJisuanqiDlg::OnButtonMul(){// TODO: Add your control notification handler code here r='*';t=true;m_mnum=m_num;m_num=0;UpdateData(FALSE);}void CJisuanqiDlg::OnButtonChu(){// TODO: Add your control notification handler code here r='/';t=true;i=10;m_cnum=m_num;m_num=0;UpdateData(FALSE);}void CJisuanqiDlg::OnButtonSub(){// TODO: Add your control notification handler code here r='-';i=10;t=true;if(j){m_snum=m_num;}else{p=0;adda[p]=m_num;p++;for(q=0;q<=p;q++){m_lnum=m_lnum+adda[q];q++;}m_num=m_lnum;UpdateData(FALSE);m_num=0;m_snum=m_lnum;}m_num=0;}void CJisuanqiDlg::OnButtonAdd(){// TODO: Add your control notification handler code here r='+';t=true;j=false;i=10;p=0;adda[p]=m_num;p++;for(q=0;q<=p;q++){m_lnum=m_lnum+adda[q];q++;}m_num=m_lnum;UpdateData(FALSE);m_num=0;}void CJisuanqiDlg::OnButtondelet(){// TODO: Add your control notification handler code here int p;p=m_num/10;m_num=p;UpdateData(FALSE);}void CJisuanqiDlg::OnButtonclear(){// TODO: Add your control notification handler code here t=true;i=10;j=true;m_num=0;m_lnum=0;UpdateData(FALSE);}void CJisuanqiDlg::OnButtonkaifang(){// TODO: Add your control notification handler code herem_num=sqrt(m_num);UpdateData(FALSE);}void CJisuanqiDlg::OnButtonziranduishu(){// TODO: Add your control notification handler code here m_num=log(m_num);UpdateData(FALSE);}void CJisuanqiDlg::OnButtonchangyongduishu(){// TODO: Add your control notification handler code here m_num=log10(m_num);UpdateData(FALSE);}。
VC 计算器程序 代码及设计思想

1.定义所有要使用的全局变量:Math_i为选择语句switch的参数,来决定进行哪种运算;Count用来进位或者退位;Input_int为某个数的整数部分,input_dec为该数的小数部分;Intput1为参与运算的第一个数,intput2为第二个数;Value作为double类型转化成Cstring类型的中间变量,存放整数部分加小数部分;Buffer字符串用来暂时存放编辑框的数字转化来的字符串;Decimal用来实现对小数点的输入;//全局变量:int math_i;double count=10,input_int=0,input_dec=0,input1=0,input2=0,value=0;char buffer[10];bool decimal=FALSE;2.以下是对数字键按钮的实现代码://数字按钮代码:void CTest329Dlg::OnButton1(){//UpdateData(TRUE);if(decimal){input_dec=input_dec+1/count;count=count*10;}else input_int=input_int*10+1;value=input_int+input_dec;gcvt(value,10,buffer);m_result=(LPCTSTR)buffer;//CTest329Dlg::m_resultUpdateData(FALSE);// TODO: Add your control notification handler code here}3.这里可有可无,作用是对按钮外观的美化://按钮位图使用代码:HBITMAPhbitmap0=::LoadBitmap(AfxGetInstanceHandle(),MAKEINTRESOURCE(IDB_BITMAP0)); m_0.SetBitmap(hbitmap0);HBITMAPhbitmap1=::LoadBitmap(AfxGetInstanceHandle(),MAKEINTRESOURCE(IDB_BITMAP1)); m_1.SetBitmap(hbitmap1);HBITMAPhbitmap2=::LoadBitmap(AfxGetInstanceHandle(),MAKEINTRESOURCE(IDB_BITMAP2)); m_2.SetBitmap(hbitmap2);HBITMAPhbitmap3=::LoadBitmap(AfxGetInstanceHandle(),MAKEINTRESOURCE(IDB_BITMAP3)); m_3.SetBitmap(hbitmap3);HBITMAPhbitmap4=::LoadBitmap(AfxGetInstanceHandle(),MAKEINTRESOURCE(IDB_BITMAP4));m_4.SetBitmap(hbitmap4);HBITMAPhbitmap5=::LoadBitmap(AfxGetInstanceHandle(),MAKEINTRESOURCE(IDB_BITMAP5));m_5.SetBitmap(hbitmap5);HBITMAPhbitmap6=::LoadBitmap(AfxGetInstanceHandle(),MAKEINTRESOURCE(IDB_BITMAP6));m_6.SetBitmap(hbitmap6);HBITMAPhbitmap7=::LoadBitmap(AfxGetInstanceHandle(),MAKEINTRESOURCE(IDB_BITMAP7));m_7.SetBitmap(hbitmap7);HBITMAPhbitmap8=::LoadBitmap(AfxGetInstanceHandle(),MAKEINTRESOURCE(IDB_BITMAP8));m_8.SetBitmap(hbitmap8);HBITMAPhbitmap9=::LoadBitmap(AfxGetInstanceHandle(),MAKEINTRESOURCE(IDB_BITMAP9));m_9.SetBitmap(hbitmap9);HBITMAPhbitmapjia=::LoadBitmap(AfxGetInstanceHandle(),MAKEINTRESOURCE(IDB_BITMAPjia)); m_jia.SetBitmap(hbitmapjia);HBITMAPhbitmapjian=::LoadBitmap(AfxGetInstanceHandle(),MAKEINTRESOURCE(IDB_BITMAPjian) );m_jian.SetBitmap(hbitmapjian);HBITMAPhbitmapcheng=::LoadBitmap(AfxGetInstanceHandle(),MAKEINTRESOURCE(IDB_BITMAPchen g));m_cheng.SetBitmap(hbitmapcheng);HBITMAPhbitmapchu=::LoadBitmap(AfxGetInstanceHandle(),MAKEINTRESOURCE(IDB_BITMAPchu)); m_chu.SetBitmap(hbitmapchu);4.等号键的实现代码。
计算器编程c语言

计算器编程 c语言用C语言设计计算器程序源代码#include <dos.h> /*DOS接口函数*/#include <math.h> /*数学函数的定义*/#include <conio.h> /*屏幕操作函数*/函数*/#include <stdio.h> /*I/O#include <stdlib.h> /*库函数*/变量长度参数表*/#include <stdarg.h> /*图形函数*/#include <graphics.h> /*字符串函数*/#include <string.h> /*字符操作函数*/#include <ctype.h> /*#define UP 0x48 /*光标上移键*/#define DOWN 0x50 /*光标下移键*/#define LEFT 0x4b /*光标左移键*/#define RIGHT 0x4d /*光标右移键*/#define ENTER 0x0d /*回车键*/void *rar; /*全局变量,保存光标图象*/使用调色板信息*/struct palettetype palette; /*int GraphDriver; /* 图形设备驱动*/int GraphMode; /* 图形模式值*/int ErrorCode; /* 错误代码*/int MaxColors; /* 可用颜色的最大数值*/int MaxX, MaxY; /* 屏幕的最大分辨率*/double AspectRatio; /* 屏幕的像素比*/void drawboder(void); /*画边框函数*/初始化函数*/void initialize(void); /*计算器计算函数*/void computer(void); /*改变文本样式函数*/ void changetextstyle(int font, int direction, int charsize); /*窗口函数*/void mwindow(char *header); /*/*获取特殊键函数*/int specialkey(void) ;设置箭头光标函数*//*int arrow();/*主函数*/int main(){设置系统进入图形模式 */initialize();/*运行计算器 */computer(); /*系统关闭图形模式返回文本模式*/closegraph();/*/*结束程序*/return(0);}/* 设置系统进入图形模式 */void initialize(void){int xasp, yasp; /* 用于读x和y方向纵横比*/GraphDriver = DETECT; /* 自动检测显示器*/initgraph( &GraphDriver, &GraphMode, "" );/*初始化图形系统*/ErrorCode = graphresult(); /*读初始化结果*/如果初始化时出现错误*/if( ErrorCode != grOk ) /*{printf("Graphics System Error: %s\n",显示错误代码*/grapherrormsg( ErrorCode ) ); /*退出*/exit( 1 ); /*}getpalette( &palette ); /* 读面板信息*/MaxColors = getmaxcolor() + 1; /* 读取颜色的最大值*/MaxX = getmaxx(); /* 读屏幕尺寸 */MaxY = getmaxy(); /* 读屏幕尺寸 */getaspectratio( &xasp, &yasp ); /* 拷贝纵横比到变量中*/计算纵横比值*/ AspectRatio = (double)xasp/(double)yasp;/*}/*计算器函数*/void computer(void){定义视口类型变量*/struct viewporttype vp; /*int color, height, width;int x, y,x0,y0, i, j,v,m,n,act,flag=1;操作数和计算结果变量*/float num1=0,num2=0,result; /*char cnum[5],str2[20]={""},c,temp[20]={""};定义字符串在按钮图形上显示的符号 char str1[]="1230.456+-789*/Qc=^%";/**/mwindow( "Calculator" ); /*显示主窗口 */设置灰颜色值*//*color = 7;getviewsettings( &vp ); /* 读取当前窗口的大小*/width=(vp.right+1)/10; /* 设置按钮宽度 */设置按钮高度 */height=(vp.bottom-10)/10 ; /*/*设置x的坐标值*/x = width /2;设置y的坐标值*/y = height/2; /*setfillstyle(SOLID_FILL, color+3);bar( x+width*2, y, x+7*width, y+height );/*画一个二维矩形条显示运算数和结果*/setcolor( color+3 ); /*设置淡绿颜色边框线*/rectangle( x+width*2, y, x+7*width, y+height );/*画一个矩形边框线*/设置颜色为红色*/setcolor(RED); /*输出字符串"0."*/outtextxy(x+3*width,y+height/2,"0."); /*/*设置x的坐标值*/x =2*width-width/2;设置y的坐标值*/y =2*height+height/2; /*画按钮*/for( j=0 ; j<4 ; ++j ) /*{for( i=0 ; i<5 ; ++i ){setfillstyle(SOLID_FILL, color);setcolor(RED);bar( x, y, x+width, y+height ); /*画一个矩形条*/rectangle( x, y, x+width, y+height );sprintf(str2,"%c",str1[j*5+i]);/*将字符保存到str2中*/outtextxy( x+(width/2), y+height/2, str2);移动列坐标*/x =x+width+ (width / 2) ;/*}y +=(height/2)*3; /* 移动行坐标*/x =2*width-width/2; /*复位列坐标*/}x0=2*width;y0=3*height;x=x0;y=y0;gotoxy(x,y); /*移动光标到x,y位置*/显示光标*/arrow(); /*putimage(x,y,rar,XOR_PUT);m=0;n=0;设置str2为空串*/strcpy(str2,""); /*当压下Alt+x键结束程序,否则执行下面的循环while((v=specialkey())!=45) /**/{当压下键不是回车时*/while((v=specialkey())!=ENTER) /*{putimage(x,y,rar,XOR_PUT); /*显示光标图象*/if(v==RIGHT) /*右移箭头时新位置计算*/if(x>=x0+6*width)如果右移,移到尾,则移动到最左边字符位置*//*{x=x0;m=0;}else{x=x+width+width/2;m++;否则,右移到下一个字符位置*/} /*if(v==LEFT) /*左移箭头时新位置计算*/if(x<=x0){x=x0+6*width;m=4;} /*如果移到头,再左移,则移动到最右边字符位置*/else{x=x-width-width/2;m--;} /*否则,左移到前一个字符位置*/if(v==UP) /*上移箭头时新位置计算*/if(y<=y0){y=y0+4*height+height/2;n=3;} /*如果移到头,再上移,则移动到最下边字符位置*/else{y=y-height-height/2;n--;} /*否则,移到上边一个字符位置*/if(v==DOWN) /*下移箭头时新位置计算*/if(y>=7*height){ y=y0;n=0;} /*如果移到尾,再下移,则移动到最上边字符位置*/else{y=y+height+height/2;n++;} /*否则,移到下边一个字符位置*/putimage(x,y,rar,XOR_PUT); /*在新的位置显示光标箭头*/ }将字符保存到变量c中*/c=str1[n*5+m]; /*判断是否是数字或小数点*/if(isdigit(c)||c=='.') /*{如果标志为-1,表明为负数*/if(flag==-1) /*{将负号连接到字符串中*/strcpy(str2,"-"); /*flag=1;} /*将标志值恢复为1*/将字符保存到字符串变量temp中*/ sprintf(temp,"%c",c); /*将temp中的字符串连接到str2中*/strcat(str2,temp); /*setfillstyle(SOLID_FILL,color+3);bar(2*width+width/2,height/2,15*width/2,3*height/2);显示字符串*/outtextxy(5*width,height,str2); /*}if(c=='+'){将第一个操作数转换为浮点数*/num1=atof(str2); /*将str2清空*/strcpy(str2,""); /*做计算加法标志值*/act=1; /*setfillstyle(SOLID_FILL,color+3);bar(2*width+width/2,height/2,15*width/2,3*height/2);显示字符串*/outtextxy(5*width,height,"0."); /*}if(c=='-'){如果str2为空,说明是负号,而不是减号*/ if(strcmp(str2,"")==0) /*设置负数标志*/flag=-1; /*else{将第二个操作数转换为浮点数*/num1=atof(str2); /*将str2清空*/strcpy(str2,""); /*act=2; /*做计算减法标志值*/setfillstyle(SOLID_FILL,color+3);画矩形*/ bar(2*width+width/2,height/2,15*width/2,3*height/2); /*显示字符串*/outtextxy(5*width,height,"0."); /*}}if(c=='*'){将第二个操作数转换为浮点数*/num1=atof(str2); /*strcpy(str2,""); /*将str2清空*/做计算乘法标志值*/act=3; /*setfillstyle(SOLID_FILL,color+3); bar(2*width+width/2,height/2,15*width /2,3*height/2);显示字符串*/outtextxy(5*width,height,"0."); /*}if(c=='/'){将第二个操作数转换为浮点数*/num1=atof(str2); /*strcpy(str2,""); /*将str2清空*/做计算除法标志值*/act=4; /*setfillstyle(SOLID_FILL,color+3);bar(2*width+width/2,height/2,15*width/2,3*height/2);outtextxy(5*width,height,"0."); /*显示字符串*/}if(c=='^'){将第二个操作数转换为浮点数*/num1=atof(str2); /*将str2清空*/strcpy(str2,""); /*做计算乘方标志值*/act=5; /*设置用淡绿色实体填充*/ setfillstyle(SOLID_FILL,color+3); /*画矩形*/ bar(2*width+width/2,height/2,15*width/2,3*height/2); /*显示字符串*/outtextxy(5*width,height,"0."); /*}if(c=='%'){将第二个操作数转换为浮点数*/num1=atof(str2); /*strcpy(str2,""); /*将str2清空*/做计算模运算乘方标志值*/act=6; /*setfillstyle(SOLID_FILL,color+3); /*设置用淡绿色实体填充*/画矩形*/ bar(2*width+width/2,height/2,15*width/2,3*height/2); /*显示字符串*/outtextxy(5*width,height,"0."); /*}if(c=='='){将第二个操作数转换为浮点数*/num2=atof(str2); /*根据运算符号计算*/switch(act) /*{case 1:result=num1+num2;break; /*做加法*/case 2:result=num1-num2;break; /*做减法*/case 3:result=num1*num2;break; /*做乘法*/case 4:result=num1/num2;break; /*做除法*/case 5:result=pow(num1,num2);break; /*做x的y次方*/case 6:result=fmod(num1,num2);break; /*做模运算*/ }设置用淡绿色实体填充*/ setfillstyle(SOLID_FILL,color+3); /*覆盖结果区*/ bar(2*width+width/2,height/2,15*width/2,3*height/2); /*将结果保存到temp中*/sprintf(temp,"%f",result); /*outtextxy(5*width,height,temp); /*显示结果*/}if(c=='c'){num1=0; /*将两个操作数复位0,符号标志为1*/num2=0;flag=1;strcpy(str2,""); /*将str2清空*/设置用淡绿色实体填充*/ setfillstyle(SOLID_FILL,color+3); /*覆盖结果区*/ bar(2*width+width/2,height/2,15*width/2,3*height/2); /*显示字符串*/outtextxy(5*width,height,"0."); /*}如果选择了q回车,结束计算程序*/if(c=='Q')exit(0); /*}putimage(x,y,rar,XOR_PUT); /*在退出之前消去光标箭头*/返回*/return; /*}/*窗口函数*/void mwindow( char *header ){int height;cleardevice(); /* 清除图形屏幕 */setcolor( MaxColors - 1 ); /* 设置当前颜色为白色*//* 设置视口大小 */ setviewport( 20, 20, MaxX/2, MaxY/2, 1 );height = textheight( "H" ); /* 读取基本文本大小 */settextstyle( DEFAULT_FONT, HORIZ_DIR, 1 );/*设置文本样式*/settextjustify( CENTER_TEXT, TOP_TEXT );/*设置字符排列方式*/输出标题*/outtextxy( MaxX/4, 2, header ); /*setviewport( 20,20+height+4, MaxX/2+4, MaxY/2+20, 1 ); /*设置视口大小*/ 画边框*/drawboder(); /*}画边框*/void drawboder(void) /*{定义视口类型变量*/struct viewporttype vp; /*setcolor( MaxColors - 1 ); /*设置当前颜色为白色 */setlinestyle( SOLID_LINE, 0, NORM_WIDTH );/*设置画线方式*/将当前视口信息装入vp所指的结构中*/getviewsettings( &vp );/*画矩形边框*/rectangle( 0, 0, vp.right-vp.left, vp.bottom-vp.top ); /*}/*设计鼠标图形函数*/int arrow(){int size;定义多边形坐标*/int raw[]={4,4,4,8,6,8,14,16,16,16,8,6,8,4,4,4}; /*设置填充模式*/setfillstyle(SOLID_FILL,2); /*/*画出一光标箭头*/fillpoly(8,raw);测试图象大小*/size=imagesize(4,4,16,16); /*分配内存区域*/rar=malloc(size); /*存放光标箭头图象*/getimage(4,4,16,16,rar); /*putimage(4,4,rar,XOR_PUT); /*消去光标箭头图象*/return 0;}/*按键函数*/int specialkey(void){int key;等待键盘输入*/while(bioskey(1)==0); /*key=bioskey(0); /*键盘输入*/只取特殊键的扫描值,其余为0*/ key=key&0xff? key&0xff:key>>8; /*return(key); /*返回键值*/}。
c语言计算器加减乘除开方混合计算和清零代码

C语言计算器加减乘除开方混合计算和清零代码一、介绍计算器是人们日常生活中常用的工具之一,通过计算器可以进行加减乘除等基本运算,还可以进行开方等复杂运算。
本文将介绍使用C语言编写计算器的加减乘除开方混合计算和清零代码。
二、加法运算代码加法运算是计算器最基本的运算之一,以下是C语言中加法运算的代码示例:```c#include <stdio.h>int m本人n() {int num1, num2, sum;printf("请输入两个整数:");scanf("d d", num1, num2);sum = num1 + num2;printf("它们的和是:d\n", sum);return 0;}```三、减法运算代码接下来是减法运算的C语言代码示例:```c#include <stdio.h>int m本人n() {int num1, num2, diff;printf("请输入两个整数:");scanf("d d", num1, num2);diff = num1 - num2;printf("它们的差是:d\n", diff);return 0;}```四、乘法运算代码乘法运算是计算器中常用的运算之一,以下是C语言中乘法运算的代码示例:```c#include <stdio.h>int m本人n() {int num1, num2, product;printf("请输入两个整数:");scanf("d d", num1, num2);product = num1 * num2;printf("它们的积是:d\n", product);return 0;}```五、除法运算代码除法运算涉及到除数不能为0的情况,以下是C语言中除法运算的代码示例:```c#include <stdio.h>int m本人n() {float num1, num2, quotient;printf("请输入两个数:");scanf("f f", num1, num2);if(num2 != 0) {quotient = num1 / num2;printf("它们的商是:.2f\n", quotient);} else {printf("除数不能为0!\n");}return 0;}```六、开方运算代码开方运算是比较复杂的运算之一,以下是C语言中开方运算的代码示例:```c#include <stdio.h>#include <math.h>int m本人n() {float num, sqrt_num;printf("请输入一个数:");scanf("f", num);if(num >= 0) {sqrt_num = sqrt(num);printf("它的开方是:.2f\n", sqrt_num);} else {printf("输入的数不能为负数!\n");}return 0;}```七、混合计算代码有时候计算器需要进行混合运算,即在一个表达式中包含多种运算,以下是C语言中混合计算的代码示例:```c#include <stdio.h>int m本人n() {float num1, num2, result;char operator;printf("请输入一个表达式(如:2+3*4):");scanf("f c f", num1, operator, num2);switch(operator) {case '+':result = num1 + num2;break;case '-':result = num1 - num2;break;case '*':result = num1 * num2;break;case '/':if(num2 != 0) {result = num1 / num2;} else {printf("除数不能为0!\n"); return 1;}break;default:printf("无效的运算符!\n"); return 1;}printf("结果是:.2f\n", result);return 0;}```八、清零代码最后一个功能是清零,即将计算器上的结果归零,以下是C语言中清零的代码示例:```c#include <stdio.h>int m本人n() {float result = 0;printf("当前结果为:.2f\n", result);char choice;printf("是否清零?(Y/N):");scanf(" c", choice);if(choice == 'Y' || choice == 'y') {result = 0;printf("已清零,当前结果为:.2f\n", result);} else if(choice == 'N' || choice == 'n') {printf("未清零,当前结果为:.2f\n", result);} else {printf("无效的输入!\n");}return 0;}```九、结论在本文中,我们以C语言的形式介绍了计算器的加减乘除开方混合计算和清零代码。
用c语言编写的计算器源代码

作品:科学计算器作者:欧宗龙编写环境:vc++6.0语言:c#include "stdafx.h"#include <stdio.h>#include <windows.h>#include <windowsx.h>#include "resource.h"#include "MainDlg.h"#include <math.h>#include <string.h>#define PI 3.141593BOOL A_Op=FALSE;BOOL WINAPI Main_Proc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {switch(uMsg){HANDLE_MSG(hWnd, WM_INITDIALOG, Main_OnInitDialog);HANDLE_MSG(hWnd, WM_MAND, Main_Onmand);HANDLE_MSG(hWnd,WM_CLOSE, Main_OnClose);}return FALSE;}BOOL Main_OnInitDialog(HWND hwnd, HWND hwndFocus, LPARAM lParam){return TRUE;}void TrimNumber(char a[])//判断并删除小数点后无用的零for(unsigned i=0;i<strlen(a);i++){if(a[i]=='.'){for(unsigned j=strlen(a)-1;j>=i;j--){if(a[j]=='0'){a[j]='\0';}else if(a[j]=='.'){a[j]='\0';}else break;}}}}double Operate(char Operator,double n1,double n2) //判断符号,进行相应的运算{if(Operator=='0'){}if(Operator=='+'){n2+=n1;}if(Operator=='-'){n2=n1-n2;}if(Operator=='*'){n2*=n1;}if(Operator=='/'){n2=n1/n2;}if(Operator=='^'){n2=pow(n1,n2);}return n2;}////////////////////////////////////////////////void IntBinary(char a[],int n){if(n>1)IntBinary(a,n/2);sprintf(a,"%s%i",a,n%2);}void decimal(char a[],double m){if(m>0.000001){m=m*2;sprintf(a,"%s%d",a,(long)m);decimal(a,m-(long)m);}}void Binary(char a[],double Num){char DecP[256]="";double x,y;double *iptr=&y;x=modf(Num,iptr);decimal(DecP,x);IntBinary(a,(int)y);strcat(a,".");strcat(a,DecP);}////////////////////////////////////void Main_Onmand(HWND hwnd, int id, HWND hwndCtl, UINT codeNotify) {static DELTIMES=0;static char str[256];static char Operator='0';static double RNum[3];switch(id){case IDC_BUTTONN1://数字1{if(A_Op){SetDlgItemText(hwnd,IDC_EDIT,NULL);}GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));strcat(str,"1");SetDlgItemText(hwnd,IDC_EDIT,str);RNum[1]=atof(str);A_Op=FALSE;}break;case IDC_BUTTONN2://数字2{if(A_Op){SetDlgItemText(hwnd,IDC_EDIT,NULL);}GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));strcat(str,"2");SetDlgItemText(hwnd,IDC_EDIT,str);RNum[1]=atof(str);A_Op=FALSE;}break;case IDC_BUTTONN3://数字3{if(A_Op){SetDlgItemText(hwnd,IDC_EDIT,NULL);}GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));strcat(str,"3");SetDlgItemText(hwnd,IDC_EDIT,str);RNum[1]=atof(str);A_Op=FALSE;}break;case IDC_BUTTONN4://数字4{if(A_Op){SetDlgItemText(hwnd,IDC_EDIT,NULL);}GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));strcat(str,"4");SetDlgItemText(hwnd,IDC_EDIT,str);RNum[1]=atof(str);A_Op=FALSE;}break;case IDC_BUTTONN5://数字5{if(A_Op){SetDlgItemText(hwnd,IDC_EDIT,NULL);}GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));strcat(str,"5");SetDlgItemText(hwnd,IDC_EDIT,str);RNum[1]=atof(str);A_Op=FALSE;}break;case IDC_BUTTONN6://数字6{if(A_Op){SetDlgItemText(hwnd,IDC_EDIT,NULL);}GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));strcat(str,"6");SetDlgItemText(hwnd,IDC_EDIT,str);RNum[1]=atof(str);A_Op=FALSE;}break;case IDC_BUTTONN7://数字7{if(A_Op){SetDlgItemText(hwnd,IDC_EDIT,NULL);}GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));strcat(str,"7");SetDlgItemText(hwnd,IDC_EDIT,str);RNum[1]=atof(str);A_Op=FALSE;}break;case IDC_BUTTONN8://数字8{if(A_Op){SetDlgItemText(hwnd,IDC_EDIT,NULL);}GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));strcat(str,"8");SetDlgItemText(hwnd,IDC_EDIT,str);RNum[1]=atof(str);A_Op=FALSE;}break;case IDC_BUTTONN9://数字9{if(A_Op){SetDlgItemText(hwnd,IDC_EDIT,NULL);}GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));strcat(str,"9");SetDlgItemText(hwnd,IDC_EDIT,str);RNum[1]=atof(str);A_Op=FALSE;}break;case IDC_BUTTONN0://数字0{if(A_Op){SetDlgItemText(hwnd,IDC_EDIT,NULL);}GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));strcat(str,"0");SetDlgItemText(hwnd,IDC_EDIT,str);RNum[1]=atof(str);A_Op=FALSE;}break;case IDC_BUTTONDEL://小数点.del{if(A_Op){SetDlgItemText(hwnd,IDC_EDIT,NULL);}GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));if(DELTIMES==0){strcat(str,".");}DELTIMES++;SetDlgItemText(hwnd,IDC_EDIT,str);A_Op=FALSE;}break;case IDC_BUTTONADD: //加法运算{RNum[1]=atof(str);RNum[0]=RNum[1];RNum[1]=RNum[2];RNum[2]=Operate(Operator,RNum[1],RNum[0]);sprintf(str,"%f",RNum[2]);TrimNumber(str);SetDlgItemText(hwnd,IDC_EDIT,str);Operator='+';DELTIMES=0;A_Op=TRUE;}break;case IDC_BUTTONSUB: //减法运算{RNum[1]=atof(str);RNum[0]=RNum[1];RNum[1]=RNum[2];RNum[2]=Operate(Operator,RNum[1],RNum[0]);sprintf(str,"%f",RNum[2]);TrimNumber(str);SetDlgItemText(hwnd,IDC_EDIT,str);DELTIMES=0;A_Op=TRUE;Operator='-';}break;case IDC_BUTTONMUL: //乘法运算{RNum[1]=atof(str);RNum[0]=RNum[1];RNum[1]=RNum[2];RNum[2]=Operate(Operator,RNum[1],RNum[0]);sprintf(str,"%f",RNum[2]);TrimNumber(str);SetDlgItemText(hwnd,IDC_EDIT,str);Operator='*';DELTIMES=0;A_Op=TRUE;}break;case IDC_BUTTONDIV: //除法运算{RNum[1]=atof(str);RNum[0]=RNum[1];RNum[1]=RNum[2];RNum[2]=Operate(Operator,RNum[1],RNum[0]);sprintf(str,"%f",RNum[2]);TrimNumber(str);SetDlgItemText(hwnd,IDC_EDIT,str);Operator='/';DELTIMES=0;A_Op=TRUE;}break;case IDC_BUTTONXY://x的y次方{GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));RNum[1]=atof(str);RNum[0]=RNum[1];RNum[1]=RNum[2];RNum[2]=Operate(Operator,RNum[1],RNum[0]);sprintf(str,"%f",RNum[2]);TrimNumber(str);SetDlgItemText(hwnd,IDC_EDIT,str);Operator='^';DELTIMES=0;}break;case IDC_BUTTONPI: //圆周率PI,弧度{GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));if(atof(str)!=0){RNum[2]=atof(str)*PI;sprintf(str,"%f",RNum[2]);TrimNumber(str);SetDlgItemText(hwnd,IDC_EDIT,str);}else{sprintf(str,"%f",PI);SetDlgItemText(hwnd,IDC_EDIT,str);}A_Op=TRUE;}break;case IDC_BUTTONSQRT: //开根号{GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));RNum[2]=sqrt(atof(str));sprintf(str,"%f",RNum[2]);TrimNumber(str);SetDlgItemText(hwnd,IDC_EDIT,str);A_Op=TRUE;}break;case IDC_BUTTONSIN: //三角函数sin函数{GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));RNum[2]=sin(atof(str));sprintf(str,"%f",RNum[2]);TrimNumber(str);SetDlgItemText(hwnd,IDC_EDIT,str);A_Op=TRUE;}break;case IDC_BUTTONCOS://三角函数cos函数{GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));RNum[2]=cos(atof(str));sprintf(str,"%f",RNum[2]);TrimNumber(str);SetDlgItemText(hwnd,IDC_EDIT,str);A_Op=TRUE;}break;case IDC_BUTTONTAN://三角函数tan函数{GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));RNum[2]=tan(atof(str));sprintf(str,"%f",RNum[2]);TrimNumber(str);SetDlgItemText(hwnd,IDC_EDIT,str);A_Op=TRUE;}break;case IDC_BUTTONSQ: //平方{GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));RNum[2]=atof(str)*atof(str);sprintf(str,"%f",RNum[2]);TrimNumber(str);SetDlgItemText(hwnd,IDC_EDIT,str);A_Op=TRUE;}break;case IDC_BUTTONCUBE://三次方{GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));RNum[2]=atof(str)*atof(str)*atof(str);sprintf(str,"%f",RNum[2]);TrimNumber(str);SetDlgItemText(hwnd,IDC_EDIT,str);A_Op=TRUE;}break;case IDC_BUTTONEX://e的x次方{GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));RNum[2]=exp(atof(str));sprintf(str,"%f",RNum[2]);TrimNumber(str);SetDlgItemText(hwnd,IDC_EDIT,str);A_Op=TRUE;}break;case IDC_BUTTON10X://10的x次方{GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));RNum[2]=pow(10,atof(str));sprintf(str,"%f",RNum[2]);TrimNumber(str);SetDlgItemText(hwnd,IDC_EDIT,str);A_Op=TRUE;}break;case IDC_BUTTONLN: //ln x{GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));RNum[2]=log(atof(str));sprintf(str,"%f",RNum[2]);TrimNumber(str);SetDlgItemText(hwnd,IDC_EDIT,str);A_Op=TRUE;}break;case IDC_BUTTONLOG10: //log10{GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));RNum[2]=log10(atof(str));sprintf(str,"%f",RNum[2]);TrimNumber(str);SetDlgItemText(hwnd,IDC_EDIT,str);A_Op=TRUE;}break;case IDC_BUTTONBINARY: //十进制转换为二进制{char a[256]="";GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));RNum[2]=atof(str);Binary(a,RNum[2]);strcpy(str,a);TrimNumber(str);SetDlgItemText(hwnd,IDC_EDIT,str);A_Op=TRUE;}break;case IDC_BUTTONCLEAR://清除数据{DELTIMES=0;Operator='0';RNum[0]=RNum[1]=RNum[2]=0;memset(str,0,sizeof(str));SetDlgItemText(hwnd,IDC_EDIT,NULL);A_Op=FALSE;}break;case IDC_BUTTONBACKSPACE://退格键{GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));int i=strlen(str);str[i-1]='\0';SetDlgItemText(hwnd,IDC_EDIT,str);}break;case IDC_ENTER://Enter键{GetDlgItemText(hwnd,IDC_EDIT,str,sizeof(str));RNum[1]=atof(str);RNum[0]=RNum[1];RNum[1]=RNum[2];RNum[2]=Operate(Operator,RNum[1],RNum[0]);sprintf(str,"%f",RNum[2]);TrimNumber(str);SetDlgItemText(hwnd,IDC_EDIT,str);Operator='0';DELTIMES=0;}break;default:break;}}void Main_OnClose(HWND hwnd){EndDialog(hwnd, 0);}本人拙作,如有不足之处请谅解。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
(10)“fabs”按钮的消息处理函数
void CMyCalculatorDlg::OnButtonFabs()
{
if( m_second==0)
{ m_first=fabs(m_first); UpdateDisplay(m_first); }
else
{ m_second=fabs(m_second); UpdateDisplay(m_second);}
{ m_first=0.0;
m_second=0.0;
m_operator = "+";
m_coff = 1.0;
UpdateDisplay(0.0);
}
(9)“n!”按钮的消息处理函数
void CMyCalculatorDlg::OnButtonJiecheng()
{
if( m_second==0)
void CMyCalculatorDlg::UpdateDisplay(double lVal)
{ //在编辑框中显示数据
m_display.Format(_T("%f"),lVal);
int i=m_display.GetLength();
while(m_display.GetAt(i-1)=='0') //格式化输出,将输出结果后的零截去
{ case '+': m_first+=m_second;break;
case '-': m_first-=m_second;break;
case '*': m_first*=m_second;break;
case '/':
if(fabs(m_second)<=0.000001)
{m_display="除数不能为0";
/
……
……
……
Button
IDC_BUTTON_CLEAR
C
Button
IDC_BUTTON9
9
Button
IDC_BUTTON_SQRT
sqrt
Button
IDC_BUTTON_POINT
.
Button
IDC_BUTTON_RECI
1/x
Button
IDC_BUTTON_SIGN
+/
Button
}
(10)“ln”按钮的消息处理函数
void CMyCalculatorDlg::OnButtonLn()
{
if( m_second==0)
{ m_first=log(m_first); UpdateDisplay(m_first); }
else
{ m_second=log(m_second); UpdateDisplay(m_second);}
}
“cos”按钮的消息处理函数
void CMyCalculatorDlg::OnButtonCos()
{
if( m_second==0)
{ m_first=cos(m_first); UpdateDisplay(m_first); }
else
{ m_second=cos(m_second); UpdateDisplay(m_second);}
{ m_display.Delete(i-1,1); i--; }
UpdateData(false);//更新编辑框变量m_display
}
void CMyCalculator::Calculate()
{ //将前一次数据与当前数据进行运算,作为下次的第一操作数,并在编辑框显示。
switch(m_operator.GetAt(0))
m_coff *= 0.1;}
UpdateDisplay(m_second);//更新编辑框的数字显示
}
void CMyCalculatorDlg::OnButtonPi()
{
m_first=3.14159265;
UpdateDisplay(m_first);
}
(2)运算符按钮的消息响应函数:
“+”按钮的消息处理函数
{m_display = "除数不能为零";
UpdateData(false);
return;}
if( fabs(m_second)<0.000001)
{ m_first=1.0/m_first;
UpdateDisplay(m_first);
}
else
{ m_second=1.0/m_second;
cos
Button
IDC_BUTTON_SIN
sin
Button
IDC_BUTTON_TAN
tan
Button
IDC_BUTTON_LN
Ln
Button
IDC_BUTTON_PI
Pi
4、为对话框类添加成员变量
1.double m_first;//存储一次运算的第一个操作数及一次运算的结果
2.double m_second;//存储一次运算的第二个操作数
UpdateData(false);
return; }
m_first/=m_second;break;
}
m_second=0.0;
m_coff=1.0;
m_operator=_T("+");
UpdateDisplay(m_first);//更新编辑框显示内容
}
7、为Button按钮的BN_CLICKED事件添加响应函数,并编写代码
}
最后在MyCalculatorDlg.cpp文件首加入语句#include <math.h>,编译并运行。
(1)数字”N”的消息响应函数(N=0,1,…9)
void CMyCalculatorDlg::OnButtonN()
{if( m_coff == 1.0)
m_second = m_second*10 + N;//作为整数输入数字时
else
{ m_second = m_second + N*m_coff; //作为小数输入数字
3.CString m_operator;//存储运算符
4.double m_coff;//存储小数点的系数权值
5.CString m_display;//编辑框IDC_DISPLAY的关联变量,显示计算结果
5、在对话框类的构造函数中,初始化成员变量
CMyCalculatorDlg::CMyCalculatorDlg(CWnd* pParent /*=NULL*/): Dialog(CMyCalculatorDlg::IDD, pParent)
void CMyCalculatorDlg::OnButtonAdd() //加、减、乘类似
{ Calculate();
m_operator="+"; //减为“-”、乘为“*”
}
void CMyCalculatorDlg::OnButtonMinus() //加、减、乘类似
{ Calculate();
UpdateDisplay(m_second);}
}
(4)“Sqrt”按钮的消息处理函数
void CMyCalculatorDlg::OnButtonSqrt()
{
if( m_second==0)
{ m_first=sqrt(m_first); UpdateDisplay(m_first); }
else
}
(11)“sin”按钮的消息处理函数
void CMyCalculatorDlg::OnButtonSin()
{
if( m_second==0)
{ m_first=sin(m_first); UpdateDisplay(m_first); }
else
{ m_second=sin(m_second); UpdateDisplay(m_second);}
}
“tan”按钮的消息处理函数
void CMyCalculatorDlg::OnButtonTan()
{
if( m_second==0)
{ m_first=tan(m_first); UpdateDisplay(m_first); }
else
{ m_second=tan(m_second); UpdateDisplay(m_second);}
{……
m_display = _T("0.0");
m_first = 0.0;
m_second= 0.0;
m_operator=_T("+");
m_coff = 1.0;
……
}
6、为对话框添加2个成员函数:
voidUpdateDisplay(double lVal)—用于在编辑框中显示数据
voidCMyCalculator::Calculate()---用于计算
VC++计算器设计
设计一个简单的计算器,能够实现浮点型数的加、减、乘、除、开方、倒数运算。运行界面如图所示。
步骤如下:
1、创建一个对话框应用程序MyCalculator;
2、在“Project Workspace”窗口,选择“Resource View”标签,双击Dialog下的“IDD_MYCALCULATOR_DIALOG”,从“IDD_MYCALCULATOR_DIALOG”对话框删除“OK”和“ Cancel”及“TODO文本”,将对话框标题设置为“计算器”。
{ m_second=sqrt(m_second); UpdateDisplay(m_second);}