所以我正在创建一个计算数字的计算器。我有这个代码(我不会包含非常基本的代码)
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 :(得分:0)
创建一个数组来保存您输入的数字和运算符,然后在输入==&#39; =&#39;时循环显示它们。让num1始终保持结果,num2保持下一个数组值。