Last active
January 2, 2016 02:09
-
-
Save zbjxb/8235262 to your computer and use it in GitHub Desktop.
给胖子的最简单的计算器四则运算
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
// 从左到右计算简单四则表达式,除数为0的话返回false | |
bool calc_exp(const char* exp, float& result); | |
int main() { | |
float result; | |
char exp[]="4-3+2*5+7/3"; | |
std::cout << "表达式: " << exp << std::endl; | |
if (!calc_exp(exp, result)) { | |
std::cout << "表达式非法\n"; | |
exit(-1); | |
} | |
else { | |
std::cout << "结果: " << result << std::endl; | |
} | |
return 0; | |
} | |
bool calc_exp(const char* exp, float& result) { | |
if (exp == NULL) { | |
return false; | |
} | |
char op; | |
float x, y; | |
const char *p = exp; | |
x = *p - '0'; | |
p++; | |
for (; *p != '\0'; p++) { | |
op = *p; | |
p++; | |
y = *p - '0'; | |
switch (op) { | |
case '+': | |
x = x + y; | |
break; | |
case '-': | |
x = x - y; | |
break; | |
case '*': | |
x = x * y; | |
break; | |
case '/': | |
if (y == 0) { | |
return false; | |
} | |
x = x / y; | |
break; | |
default: | |
return false; | |
} | |
} | |
result = x; | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment