Vekash
Vekash

Reputation: 7

How to calculate percentage in a calculator that takes whole input as a String?

public static int applyOp(char op, int b, int a) {
    switch (op) {
        case '+':
            return a + b;
        case '-':
            return a - b;
        case '*':
            return a * b;
        case '%':
            return a % b;  //But this doesn't work properly.
        case '/':
            if (b == 0)
                throw new
                        UnsupportedOperationException("Cannot divide by zero");
            return a / b;
    }
    return 0;
}

}

i tried this using 100*10+2, 525+5%, 525*5% but other operators work properly but '%' doesn't.

Upvotes: 0

Views: 115

Answers (2)

Basil jose
Basil jose

Reputation: 779

public static int applyOp(char op, int b, int a) {
    switch (op) {
        case '+':
            return a + b;
        case '-':
            return a - b;
        case '*':
            return a * b;
        case '%':

            return (int)(((float) a / b) * 100);
        case '/':
            if (b == 0)
                throw new
                        UnsupportedOperationException("Cannot divide by zero");
            return a / b;
    }
    return 0;
}

}

while using % it will return the modulus [remainder] for the division a by b

Upvotes: 1

Roman Puchkovskiy
Roman Puchkovskiy

Reputation: 11865

% operator computes a reminder and not percentage.

If you want to compute 'how many percents is a of b?', you could use something like this:

(int) (((float) a / b) * 100)

You need to cast to float to use floating point division instead of integer division (that would be used for just a/b) to not loose precision before multiplying by 100.

Another option is to multiply first:

a * 100 / b

But here you could potentially get an integer overflow if a is large in magnitude.

Upvotes: 0

Related Questions