0

I'realy don't understand how divide doubles in c++ and have the correct precision.

I read many posts and undertood the logic (What Every Computer Scientist Should Know About Floating-Point Arithmetic) but I dont see how I can do. Could you help me :-)

#include <stdio.h>
#include <iostream>
#include <math.h>

int main(int argc, char const *argv[])
{
    //Convert 123 minutes in hh:mm

    double a(123); //Minutes in decimal format
    
    double resultat = a/60.0;

    //resultat = 2.0499999999999998 and not 2.05
    double hours;
    double decimalMinute;
    
    decimalMinute = modf(resultat, &hours);
    
    int minutes = decimalMinute*60.0;
    //Give 2 and not 3 !!!

    double minutesDouble = decimalMinute*60.0;
    //Give 2,999999 and not 3 !!

    return 0;
}

How can I have the "correct" value ?

atr
  • 1
  • 2
    the values are "correct" – 463035818_is_not_an_ai Mar 22 '22 at 10:10
  • 1
    if you want precise results do not use floating point numbers. In your example fixed point numbers with 2 decimals are sufficient to get precise results – 463035818_is_not_an_ai Mar 22 '22 at 10:11
  • 2
    *I dont see how I can do* - hint: you don't need floating point math in your example. Integer division and integer modulo is what you need. – Yksisarvinen Mar 22 '22 at 10:12
  • https://godbolt.org/z/f7j5chjGq – 463035818_is_not_an_ai Mar 22 '22 at 10:16
  • 1
    You didn't understand the logic. – molbdnilo Mar 22 '22 at 11:42
  • Thank @463035818_is_not_a_number for your feed back. I don't want use ``std::out`` but use the result. If i add the code bellow, I always have error because minutesDouble is not equal to 3. What can I do ? ``if (minutesDouble != double(3.0)){ std::cout << "Erreur : " << minutesDouble; } else { std::cout << "OK"; }`` @Yksisarvinen : Hour & minutes are only an example. This conversion is not my goal. – atr Mar 22 '22 at 15:58
  • what i already said: If you need exact numbers, do not use floating point numbers. Why is `minutesDouble` a `double` at all? `123 % 3` is `3` exact – 463035818_is_not_an_ai Mar 22 '22 at 17:11

0 Answers0