2014-03-12 27 views
0

所以我創建一個計算器,將計算numbers.I有這樣的代碼(我將不包括非常基本的代碼)計算多個號碼與多個操作

long num1, num2, answer; 
boolean mySwitch = false; 
boolean do_subtraction_flag = false; // when true we will apply subtraction 
boolean multiply = false; 
boolean divide = false; 

void loop() 
{ 
char keypressed = myKeypad.getKey(); 

if(keypressed != NO_KEY) 
{ 
    Serial.print(keypressed); 



    if(keypressed > 47 && keypressed < 58) // is between '0' and '9' 
    { 
     if(!mySwitch) 
     { 
      num1 = (num1 * 10) + (keypressed - 48); 
     } 
     else 
     { 
      num2 = (num2 * 10) + (keypressed - 48); 
     } 



    } 

    if(keypressed == '=') 
    { 
     if(do_subtraction_flag) // we want to subtract the numbers 
     { 
      answer = num1 - num2; 
     }else if(multiply){ 

    answer = num1 * num2; 
    }else if(divide){ 
    answer = num1/num2; 
    } 
     else // we want to add the numbers 
     { 
      answer = num1 + num2; 
     } 

     Serial.println(answer); 
     num1 = 0; 
     num2 = 0; 
     mySwitch = false; 
     do_subtraction_flag = false; 
    multiply = false; 
    divide = false; 
    } 
    else if(keypressed == '+') 
    { 
     mySwitch = true; 
    } 
else if(keypressed == '*'){ 
    mySwitch = true; 
    multiply = true; 
}else if(keypressed == '/'){ 
    mySwitch = true; 
    divide = true; 
} 
    else if(keypressed == '-') 
    { 
     mySwitch = true; 
     do_subtraction_flag = true; 
    }else if (keypressed == 'C'){ 
     for (int i=0; i < 80; i++) 
     { 
     Serial.write(8); // print 80 times backspace (BS) 
    }   
    } 
} 
} 

林困惑在這裏,因爲我想計算倍數與多個操作數(例如,2 + 1 + 3或2 + 1-2),但是當我添加另一個變量'num3'我應該怎麼處理它?如果我把它放到do_subtraction標誌中,如果用戶輸入2-1 + 3會怎麼樣?是否可以用這個代碼計算3個數字?我在這裏感到困惑,但是讓我知道你是否也困惑我想做什麼

回答

0

創建一個數組來保存您輸入的數字和運算符,然後在輸入=='='時循環它們。讓你的num1總是保存結果,num2保存下一個數組值。