4 years, 9 months ago.

UART/SERIAL CALCULATOR HELP

I think I have the code for a single digit 4 function calculator, the interface is the terminal

I need help changing this code to a 2 digit 4 function calculator, any help is appreciated.

the code is attached /media/uploads/larcoc/final_project_micro2.docx

thanks for the quick response!

posted by Carlos Larco 02 Apr 2015

1 Answer

4 years, 9 months ago.

A very very simple way of doing it. I write simple because there is no check about the char to verify if it is an digit or other.

#include "mbed.h"              
 
Serial pc(USBTX, USBRX);
 
 
int main() 
{
    while(1) 
    {
    int num1;
    int num2;
    int func;
    int sol;
    char a;
    
    pc.printf("enter first number\n");
     a = pc.getc();
    num1 =( a - 48)*10;   // first digit * 10;
    a = pc.getc();
    num1 += a=48;

    pc.printf("%d\n ", num1);
    pc.printf("enter second number\n");

    a = pc.getc();
    num2 =( a - 48)*10;   // first digit * 10;
    a = pc.getc();
    num2 += a=48;        // add to num1 the digit.

    pc.printf("%d\n ", num2);
    pc.printf("enter function (1 for add, 2 for subtract, 3 for multiply, 4 for divide)\n");
    char c = pc.getc();
    func = c - 48;
    pc.printf("%d\n ", func);

    
    if (func == 1)
    {
    pc.printf("solution\n");
    sol = (num1 + num2);
    pc.printf("%d\n ", sol);

        }
    if (func == 2)
    {
    pc.printf("solution\n");
    sol = (num1 - num2);
    pc.printf("%d\n ", sol);
        }
    if (func == 3)
    {
    pc.printf("solution\n");
    sol = (num1 * num2);
    pc.printf("%d\n ", sol);
        }
    if (func == 4)
    {
    pc.printf("solution\n");
    sol = (num1 / num2);
    pc.printf("%d\n ", sol);
        }
    }
}

to check if the char is a digit you could use something like :

do
{
   a = pc.getc()-'0';     
} while (a<0 || a>9);



Accepted Answer

Personally I'd replace the series of if (func== n ) with a single switch statement. It makes the code more readable:

      switch(func) {
      case 1:
        pc.printf("solution\n%d\n",num1+num2);
        break;
      case 2:
        pc.printf("solution\n%d\n",num1-num2);
        break;
      case 3:
        pc.printf("solution\n%d\n",num1*num2);
        break;
      case 4:
        if (num2 !=0)
          pc.printf("solution\n%.2f\n",(float)num1/num2); // slightly different so that it doesn't round down to the nearest whole number.
       else
         pc.printf("division by 0 error\n");
        break;
     default:
         pc.printf("invalid function\n");
         break;
  }

posted by Andy A 02 Apr 2015

num1 += a=48; was this statement supposed to be num1 += a - 48; ?

posted by Carlos Larco 02 Apr 2015

yes mistake from me :

one must read : num1 += a - 48;

posted by Raph Francois 02 Apr 2015