MFC代码--基于对话框的计算器设计

MFC的作业

  • 编写一个计算器程序。使用该计算机使用编辑控件直接输入数据,并有加减乘除、平方根和倒数运算功能。
  • 简要分析:用AppWizard生成一个基于对话框的应用程序框架,编辑对话框模版资源,添加一个编辑控件,添加8个按钮,设置下ID和Caption。 ### 代码部分
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    void CCalculatorDlg::OnSetfocusInput()
    {
    m_fInput=0.0;
    UpdateData(FALSE);
    // TODO: Add your control notification handler code here
    }
    void CCalculatorDlg::OnAdd()
    {
    OnCalc();
    m_nOP=1;
    // TODO: Add your control notification handler code here
    }
    void CCalculatorDlg::OnCalc()
    {
    // TODO: Add your control notification handler code here
    UpdateData(TRUE);
    switch(m_nOP)
    {
    case 0:
    m_fResult=m_fInput;
    break;
    case 1:
    m_fResult+=m_fInput;
    break;
    case 2:
    m_fResult-=m_fInput;
    break;
    case 3:
    m_fResult*=m_fInput;
    break;
    case 4:
    m_fResult/=m_fInput;
    break;
    case 5:
    m_fResult=1/m_fInput;
    break;
    case 6:
    m_fResult=sqrt(m_fInput);
    break;
    }
    m_fInput=m_fResult;
    UpdateData(FALSE);
    }
    void CCalculatorDlg::OnClear()
    {
    // TODO: Add your control notification handler code here
    m_fResult=0.0;
    m_fInput=0.0;
    m_nOP=0;
    UpdateData(FALSE);
    }
    void CCalculatorDlg::OnDiv()
    {
    OnCalc();
    m_nOP=4;
    // TODO: Add your control notification handler code here
    }
    void CCalculatorDlg::OnMul()
    {
    OnCalc();
    m_nOP=3;
    // TODO: Add your control notification handler code here
    }
    void CCalculatorDlg::OnReciprocal()
    {
    m_nOP=5;
    OnCalc();
    m_nOP=0;
    // TODO: Add your control notification handler code here
    }
    void CCalculatorDlg::OnSqrt()
    {
    // TODO: Add your control notification handler code here
    m_nOP=6;
    OnCalc();
    m_nOP=0;
    }
    void CCalculatorDlg::OnSub()
    {
    OnCalc();
    m_nOP=2;
    // TODO: Add your control notification handler code here
    }

省略了一些声明和初始化代码。 ### 小结 新知识主要有:
为编辑控件的消息EN_SETFOCUS添加一个映射函数OnSetfocusInput()。 对话框类的成员函数UpdateData()用于更新数据。