Create a grammar for a calculator that operates using the four operations only (ADD, SUB, MUL, DIV) over hexadecimal numbers.
#include<stdio.h>
#include<conio.h>
#include<math.h>
int hexToDecimal (char hexnum[]) {
int decnum = 0, rem, i = 0, len = 0;
while (hexnum[i] != '\0') {
len++;
i++;
}
len--;
i = 0;
while (len >= 0) {
rem = hexnum[len];
if (rem >= 48 && rem <= 57)
rem = rem - 48;
else if (rem >= 65 && rem <= 70)
rem = rem - 55;
else if (rem >= 97 && rem <= 102)
rem = rem - 87;
else {
printf("\nYou've entered an invalid Hexadecimal digit");
}
decnum = decnum + (rem * pow(16, i));
len--;
i++;
}
return decnum;
}
int main() {
int firstDecNumber, secondDecNumber;
char first[20], second[20];
char operator;
printf("Enter an operator (+, -, *,): ");
scanf("%c", &operator);
printf("Enter two operands: \n");
printf("Enter first Hexadecimal Number: ");
scanf("%s", first);
printf("Enter second Hexadecimal Number: ");
scanf("%s", second);
firstDecNumber = hexToDecimal(first);
secondDecNumber = hexToDecimal(second);
switch (operator) {
case '+':
printf("%d + %d = %d", firstDecNumber, secondDecNumber, firstDecNumber + secondDecNumber);
break;
case '-':
printf("%d - %d = %d", firstDecNumber, secondDecNumber, firstDecNumber - secondDecNumber);
break;
case '*':
printf("%d * %d = %d", firstDecNumber, secondDecNumber, firstDecNumber * secondDecNumber);
break;
// operator doesn't match any case constant
default:
printf("Error! operator is not correct");
}
getch();
return 0;
}
Comments
Leave a comment