0

This is my code:

public int raiseSalary (int percent){
    return salary + (salary*(percent/100))
} // here the output is 5000 (every time the output is the same salary)

When I run the program with EX: 5000 salary and raise by 10% it should by 5500

But

The strange thing here when I reweite the code in the following form it’s work correctly!

public int raiseSalary (int percent){
    return salary + (salary* percent/100)

} //here the output is 5500 which is true

What is the problem with first code!

Turing85
  • 16,432
  • 7
  • 31
  • 51
Fajer
  • 1
  • 1
  • 1
    Integer division.... Try `/ 100.0` – OneCricketeer Nov 09 '21 at 20:48
  • 1
    Since `percent` is an `int` (and probably `< 100`), `percent / 100` will evaluate to `0` because `int`-division rounds towards `0`. – Turing85 Nov 09 '21 at 20:48
  • `percent` is an `int`, thus `percent / 100` is integer division. You can tix this by dividing by `100.0` (for floating point division) – Proof-By-Sledgehammer Nov 09 '21 at 20:50
  • 1
    @OneCricketeer It should be mentioned that this changes the type of the whole expression to `double`. Thus we would have to either cast the result back to `int` or change the return-type to `double`. – Turing85 Nov 09 '21 at 20:51
  • 1
    @Turing85 Or the method could (and probably should) return `BigDecimal` for dealing with currency types – OneCricketeer Nov 09 '21 at 20:52

0 Answers0