How to write a C Program to Calculate 2 numbers with 1 operation in C Programming Language ?
Reverse Polish Notation - C Program to Calculate 2 numbers with 1 operation.
Solution:
- #include<stdio.h>
- //calculate 2 numbers with 1 operation
- double calc (char operator, double a, double b) {
- double result = 0;
- switch (operator) {
- case '+':
- result = a + b;
- break;
- case '-':
- result = a - b;
- break;
- case '*':
- result = a * b;
- break;
- case '/':
- result = a / b;
- break;
- }
- printf("[DEBUG] %lf %lf %c = %lf\n", a, b, operator, result);
- return result;
- }
- int main (void) {
- //declare new char array in c style
- char term[256] = {0};
- //declare variable for result
- double result = 0;
- printf("Please insert your calculation: \n");
- //read term from input stream stdin
- fgets(term, 255, stdin);
- printf("Your input: %s\n", term);
- //declare variables for numbers between operation
- double a = 0;
- double b = 0;
- int k = 0;
- char lastNumber[256] = {0};
- int numberCounter = 0;
- int lineSpaceCounter = 0;
- int lastCharType = 0; //1 - number, 2 - operator
- //parse string
- for (int i = 0; i < 256; i++) {
- //check if char is line break
- if (term[i] == '\n') {
- break;
- }
- //converts '0' to 0, '1' to 1
- double number = term[i] - '0';
- if (number >= 0 && number <= 9) {
- //its an number, add number to term
- lastNumber[k] = term[i];
- //increment counter
- k++;
- lineSpaceCounter = 0;
- lastCharType = 1;
- } else if (term[i] == ' ') {
- //its an line space, so save last number
- //convert char array to integer
- double n = 0;
- sscanf(lastNumber, "%lf", &n);
- printf("[DEBUG] %s %lf\n", lastNumber, n);
- //save last number into a or b
- if (numberCounter == 0) {
- //save lastNumber into a
- a = n;
- } else {
- //save lastNumber into b
- b = n;
- }
- //increment line space counter, break on 2 line spaces too
- lineSpaceCounter++;
- numberCounter++;
- //because an number size be more than 1 char, we need this counter variable
- k = 0;
- } else if (term[i] == '+' || term[i] == '-' || term[i] == '*' || term[i] == '/') {
- //its an operator, so calculate sub term
- result = calc(term[i], a, b);
- a = result;
- numberCounter = 1;
- k = 0;
- lineSpaceCounter = 0;
- lastCharType = 2;
- }
- }
- //print result
- printf("Result: %lf\n", result);
- return 0;
- }
- /*
- * Copyright (c) 2015 Justin Kuenzel, All Rights reserved.
- *
- * MIT License, https://opensource.org/licenses/MIT
- */