testing-repository/Gtkmm3/gtk131_calc2/src/calc.cc

71 lines
2.0 KiB
C++
Raw Normal View History

2022-06-09 16:27:22 +08:00
#include <iostream>
#include <cstdlib>
#include <cstring>
#include "calc.hh"
static int pos = 0;
void calc_reset(){
pos = 0;
}
2022-06-22 19:07:25 +08:00
double calc_factor_value(const char * factor){
2022-06-22 19:54:24 +08:00
double result1 = 0.0, result2 = 0.0;
2022-06-09 16:27:22 +08:00
char c = factor[pos];
if( c == '('){ // if expression has '(', calculate the expression in the '()'
2022-06-22 19:54:24 +08:00
pos++; // Pass the '('
result1 = calc_expression_value(factor);
pos++; // Pass the ')'
2022-06-09 16:27:22 +08:00
}else{
while(isdigit(c)){ // Get the number to calculate
2022-06-22 19:54:24 +08:00
result1 = 10 * result1 + c - '0';
2022-06-09 16:27:22 +08:00
pos++;
c = factor[pos];
}
2022-06-22 19:54:24 +08:00
if(c == '.'){ // Get number between 0 to 1
pos++; // Pass the '.'
c = factor[pos];
while(isdigit(c)){
result2 = 0.1 * result2 + (c - '0') * 0.1;
pos++;
c = factor[pos];
}
}
2022-06-09 16:27:22 +08:00
}
2022-06-22 19:54:24 +08:00
return result1+result2;
2022-06-09 16:27:22 +08:00
}
2022-06-22 19:07:25 +08:00
double calc_term_value(const char * term){
double result = calc_factor_value(term); // Get the first number
2022-06-09 16:27:22 +08:00
while(true){
//pos++; // Calc the multiplication and divide
char op = term[pos];
if(op == '*' || op == '/'){
pos++;
2022-06-22 19:07:25 +08:00
double value = calc_factor_value(term); // Get another value
2022-06-09 16:27:22 +08:00
if(op == '*') result *= value;
else result /= value;
}else{
break;
}
}
return result;
}
2022-06-22 19:07:25 +08:00
double calc_expression_value(const char * expression){
double result = calc_term_value(expression); // Calc the result of expression
2022-06-09 16:27:22 +08:00
//bool more = true;
while(true){
char op = expression[pos];
if(op == '+' || op == '-'){ // Calculate for add and subb
pos++;
2022-06-22 19:07:25 +08:00
double value = calc_term_value(expression);
2022-06-09 16:27:22 +08:00
if( op == '+') result += value;
else result -= value;
}else{
break;
}
}
return result;
}