Reputation: 53
I wrote a calculator program in C but it doesnt work as intended. P is an acumulator that stores the current number, its like a memory of calculator. if you want to perform an operation, like +, you do P + , it doesnt matter if + or numbers are on different lines, blank spaces dont count. My code works for P 20 + 20 as intended. If you want to get the result you type =. So if You input P 20 + 20 = , the result should be 40. For P 20 + 20 + 20 the result should be 60, however, in my program its still 40. I will attach photos of my inputs and the expected inputs.
Code:
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
void print_error_message(char *message)
{
fprintf(stderr, "%s\n", message);
}
bool calculate(void)
{
int ch;
int akumulator = 0;
int number = 0;
char operation = 0;
while ((ch = getchar()) != EOF)
{
if (ch == '\n' || ch == ' ') {
continue;
}
switch(ch)
{
case 'P':
operation = 1;
akumulator = 0;
break;
case '+':
number = 0;
operation = 2;
break;
default:
;
}
if (operation == 1)
{
if (isdigit(ch)){
akumulator = (akumulator * 10) + (ch - '0');
}
}
if (operation == 2)
{
if (isdigit(ch)){
number = (number * 10) + (ch - '0');
} else{
akumulator = akumulator + number;
}
}
if ((operation == 0) && isdigit(ch))
{
print_error_message("Syntax error");
return false;
}
if (operation != 0)
{
if (ch == '=' || ch == ';' || ch == '+')
{
printf("# %d", akumulator);
putchar('\n');
}
if (ch == EOF)
{
printf("# %d", akumulator);
putchar('\n');
}
}
if (ch == '=')
{
printf("# %d", akumulator);
putchar('\n');
}
}
print_error_message("SYNTAX ERROR");
return false;
}
int main(void)
{
if (!calculate()) {
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
Upvotes: 1
Views: 214
Reputation: 3530
Reset the number only after incrementing it in the accumulator. See the below code (commented the modified parts):
while ((ch = getchar()) != EOF)
{
if (ch == '\n' || ch == ' ') {
continue;
}
switch(ch)
{
case 'P':
operation = 1;
akumulator = 0;
break;
case '+':
//removed the number reset
operation = 2;
break;
default:
;
}
if (operation == 1)
{
if (isdigit(ch)){
akumulator = (akumulator * 10) + (ch - '0');
}
}
if (operation == 2)
{
if (isdigit(ch)){
number = (number * 10) + (ch - '0');
} else{
akumulator = akumulator + number;
number = 0; // number is resetted here!
}
}
if ((operation == 0) && isdigit(ch))
{
print_error_message("Syntax error");
return false;
}
if (operation != 0)
{
if (ch == '=' || ch == ';' || ch == '+')
{
printf("# %d", akumulator);
putchar('\n');
}
if (ch == EOF)
{
printf("# %d", akumulator);
putchar('\n');
}
}
if (ch == '=')
{
printf("# %d", akumulator);
putchar('\n');
}
}
Upvotes: 1