2015-11-07 53 views
-3

所以我试图让一个计算器与多个运算符一起工作。我制作了一些计算器程序,使用2个数字(使用开关),但是当我尝试使用2个以上的数字时,我无法真正使其工作。我有一个想法如何做到这一点,但我不能实现它(我是编程新手)。这行不行,但这是我的想法:result = a op [0] b op [1] c; 因此,这里的代码:C++多个运算符计算器

// Simple arithmetic calculator. 
#include <iostream> 
using namespace std; 


int main() 
{ 
    float a, b, c, result; 
    char op[2]; 

    // Get numbers and mathematical operator from user input 
    cin >> a >> op[0] >> b >> op[1] >> c; 
result = a op[0] b op[1] c; // result = a + b - c if op[0]=+ and op[1]=- 
    // Output result 
    cout << result << endl; 
    return 0; 
} 

这里的其他代码,但不工作

// CalculatorSwitch.cc 
// Simple arithmetic calculator using switch() selection. 

#include <iostream> 
using namespace std; 

int main() 
{ 
    float a, b, c, result; 
    char operation,operation2; 

    // Get numbers and mathematical operator from user input 
    cin >> a >> operation >> b >> operation2 >> c; 

    // Character constants are enclosed in single quotes 
    switch(operation) 
    { 
    case '+': 
     result = a + b; 
     break; 

    case '-': 
     result = a - b; 
     break; 

    case '*': 
     result = a * b; 
     break; 

    case '/': 
     result = a/b; 
     break; 

    default: 
     cout << "Invalid operation. Program terminated." << endl; 
     return -1; 
    } 
    switch(operation2) 
    { 
    case '+': 
     result = b + c; 
     break; 

    case '-': 
     result = b - c; 
     break; 

    case '*': 
     result = b * c; 
     break; 

    case '/': 
     result = b/c; 
     break; 

    default: 
     cout << "Invalid operation. Program terminated." << endl; 
     return -1; 
    } 
} 

所以,如果我是正确的,以超过2个号码使用它,我必须创建一个第二开关第二个操作符,但我得到了错误的结果..所以我想让第一个代码工作。

+1

你没有注意到,这甚至不会编译? –

+0

如果'switch'使用两个数字,为​​什么不使用例如这里开关三个数字? – SaschaP

回答

0

你的逻辑错了。在第一个switch语句中,您设置了result = a OP1 b。在第二台交换机中,您设置了result = b OP2 c,完全覆盖了第一台交换机的功能。相反,您必须处理中间结果,例如改变你的第二个开关,但是

switch(operation2) 
{ 
case '+': 
     result = result + c; 
     break; 

case '-': 
     result = result - c; 
     break; 

case '*': 
     result = result * c; 
     break; 

case '/': 
     result = result/c; 
     break; 

default: 
     cout << "Invalid operation. Program terminated." << endl; 
     return -1; 
} 

注意,这仍是不正确的,因为它忽略了操作的顺序,如果第一个运营商+-,第二个是*/

为了使第一个代码有效,它不仅仅需要这个答案,而是创建一个完整的数学分析器并不重要。