1
double res = (double)((a*b)/(a+b));

After trying the above code with inputs 80,70 I am getting the output 37 not 37.333 but after removing one parenthesis i got the right answer.

The right code is:

double res = (double)(a*b)/(a+b);

I am using: gcc version 9.3.0 (Ubuntu 9.3.0-10ubuntu2)

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
  • 1
    1. First Case double res = (double)((a*b)/(a+b)); In this case, for the input 80 and 70, the evaluation goes as -> res = (double)((70*80)/(70+80)) = (double)((5600)/(150)) = (double)(37) = 37 2. Second Case double res = (double)(a*b)/(a+b); In this case, for the input 80 and 70, the evaluation goes as -> res = (double)(70*80)/(70+80) = (double)(5600)/(150) = 5600.0/150 = 37.33 – Abhishek Bhagate Sep 07 '20 at 18:14
  • Worked for me. I even simplified with less parens and no unnecessary cast. `double a = 80; double b = 70; double res = (a*b)/(a+b);` – Eljay Sep 07 '20 at 21:39

1 Answers1

2
double res = (double)((a*b)/(a+b));

Casting to double after integer math is applied, where values might have been truncated. Resort to operator precedence.

double res = (double)(a*b)/(a+b);

Here the cast is performed before the divison.

Tony Tannous
  • 14,154
  • 10
  • 50
  • 86