0

So basically I must make it work with multiplication as well with signs.For example 2*2=4 but 2*-2=-4 and i cant find a proper way to do it.Any advice would be helpful.My code so far is :

#include <stdio.h>
#include <stdlib.h>

int main ( void )
{
    int result = 0, val = 1, ch, howmany = 1, number = 0;
    while ( ( ch = getchar() ) != EOF )
    {
        if ( ch == ' ' || ch == '\t' )
            continue;
        else if ( ( ch >= '0' ) && ( ch <= '9' ) )
            number = number * 10 + ( ch - '0' );
        else if ( ch == '+' )
        {
            result += ( number * val );
            val = 1;
            number = 0;
        }
        else if ( ch == '-' )
        {
            result += ( number * val );
            val = -1;
            number = 0;
        }
        else if ( ch == '\n' )
        {
            howmany++;
            result += ( number * val );
            printf( "%d\n", result);
        number = 0;
        result = 0;
        val = 1;
    }
}
 }
dbush
  • 205,898
  • 23
  • 218
  • 273

1 Answers1

1

The code is zeroing the result on every loop iteration.

It seems like it should only do this after printing the result variable.

    else if ( ch == '\n' )
    {
        howmany++;
        result += ( number * val );
        printf( "%d\n", result );
    }
    number = 0;
    result = 0;
    val = 1;

Should be:

    else if ( ch == '\n' )
    {
        howmany++;
        result += ( number * val );
        printf ( "%d\n", result );

        number = 0;
        result = 0;
        val = 1;
    }

With this change, it works for me (pressing [enter] after each arithmetic expression):

$ ./calc_code
1+1
2
3+2
5
-1+1
0
7+2
9
7-2
5
7+13
20
Kingsley
  • 14,398
  • 5
  • 31
  • 53
  • First of all thanks for the help.In order to complete it I must make it work with multiplication as well with signs.For example 2*2=4 but 2*-2=-4 and i cant find a proper way to do it.Any advice would be helpful. –  Dec 05 '18 at 13:06
  • @mouratios Maybe you could consider handling brackets, and when you read `(` store the current result, calculate the next expression until a `)` is read. Note also that when you hit 2 operators together, it should always be this `[any operator][-]Value` form (or a syntax error). Googling "parsing numerical expressions" should give you a few ideas too. – Kingsley Dec 05 '18 at 22:05