Last active
September 7, 2019 17:05
-
-
Save ChlorUpload/ae2f9f1faaa18d93ae5414b92e1d1296 to your computer and use it in GitHub Desktop.
A calculator recognizing addition and multiplication
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <string.h> | |
#include <stdbool.h> | |
#define MAX 128 | |
bool is_digit(char ch) { return (ch >= '0' && ch <= '9'); } | |
int main(void) | |
{ | |
bool mul = false; | |
int number[MAX], cnt = 0; | |
char expression[MAX]; | |
scanf_s("%s", expression, MAX); | |
int i, sum = 0; | |
for (i = 0; i <= strlen(expression); i++) | |
{ | |
if (is_digit(expression[i])) | |
{ | |
sum *= 10; | |
sum += (int)(expression[i] - '0'); | |
} | |
else | |
{ | |
if (mul) | |
{ | |
number[cnt - 1] *= sum; | |
sum = 0; | |
mul = false; | |
} | |
else | |
{ | |
number[cnt] = sum; | |
cnt++; | |
sum = 0; | |
} | |
if (expression[i] == '*') | |
{ | |
mul = true; | |
} | |
} | |
} | |
for (i = 0; i < cnt; i++) | |
{ | |
printf("\n%d", number[i]); | |
sum += number[i]; | |
} | |
printf("\n%d", sum); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment