0

input are 2 float numbers: num1, num2, calculate num = num1*num2.

Eg: num1 = 2.09,num2 = 33.85 num = num1 * num2 = 70.74649 num's accurate value is 70.7465

I know we can choose to convert float to int value first by:

    int intNum1 = num1 * 100;
    int intNum2 = num2 * 100;
    int intNum = intNum1 * intNum2;
    num = intNum / 10000;

Is there another solution to get accurate result? thanks.

doit
  • 29
  • 3
  • The duplicate is admittedly more about why this does not work as you hope it would. A possible solution (in your case) would be to use a decimal floating point type. – chtz May 23 '21 at 17:11
  • 1
    doit, Certainly `int intNum = num1 * num2;` should have been `int intNum = intNum1 * intNum2;`. – chux - Reinstate Monica May 24 '21 at 08:26
  • `int intNum1 = num1 * 100;` better as `int intNum1 = lroundf(num1 * 100);`. Form a rounded answer rather than a truncated one. Leads to `70.746490478515625`, closest `float` to `70.7465`. – chux - Reinstate Monica May 24 '21 at 08:32
  • I make a small mistake. Thank chux, I have corrected the sentence:int intNum = intNum1 * intNum2; – doit Jun 14 '21 at 01:41

0 Answers0