标签:case turn ane printf exp div stream test main
#pragma once class Counter { public: void setExp(const char* exp);//设置表达式 void cleanExp(); //清除表达式 void countExp();//计算表达式 int reExp();//返回结果 private: char m_exp[20]; int m_Num1; int m_Num2; int sum; void sub(int n);//整理表达式,分离两个两个运算数 };
counter类 counter.h
counter.cpp
#include "Counter.h" #include <string.h> #include <stdlib.h> void Counter::setExp(const char* exp) { strcpy_s(m_exp, 20, exp); } void Counter::sub(int n) { char num1[20]; char num2[20]; int len=strlen(m_exp); for (int i=0;i<len;i++) { if (i<n) { num1[i] = m_exp[i]; } if (i>n) { num2[i - n-1] = m_exp[i]; } } m_Num1 = atoi(num1); m_Num2 = atoi(num2); } void Counter::cleanExp() { strcpy_s(m_exp, 20, 0); } void Counter::countExp() { for (int i=0;i<20;i++) { switch (m_exp[i]) { case ‘+‘: { sub(i); sum = m_Num1 + m_Num2; }break; case ‘-‘: { sub(i); sum = m_Num1 - m_Num2; } break; case ‘*‘: { sub(i); sum = m_Num1 * m_Num2; } break; case ‘/‘: { sub(i); sum = m_Num1 / m_Num2; } break; default: break; } } } int Counter::reExp() { return sum; }
测试test.cpp
#include <iostream>
#include <stdio.h>
#include "Counter.h"
int main()
{
Counter count;
char str[20];
printf("请输入所需要计算的表达式:");
scanf_s("%s",str,20);
count.setExp(str);
count.countExp();
std::cout << "结果为:"<<count.reExp() << std::endl;
}
标签:case turn ane printf exp div stream test main
原文地址:https://www.cnblogs.com/mountainCold/p/11191002.html