Hanging when working with basic types in Qt



  • In a program, I want to display the number 0.12345 as .12345 (removing the first zero) in a lineEdit. For this I wrote the simple code below:

    QString s;
    QTextStream ss(&s);
    
      double temp = 0.12345;
      int n = 0;
    
     if(temp > 0)
        {
          ss << ".";
         while(true)
           {
             temp *= 10;
             n = temp;
             if(temp == n)
                 break;
           }
         ss << n;
      }
    
     lineEdit-> setText(s);
    

    When I run the it, the compiler (Qt Creator) hangs and I need to rerun the code to normally go out of it.

    What is the problem that the compiler acts that way, please, and how to solve it?


  • Moderators

    @tomy

    You programmed an endless loop!

    Not the compiler nor Qt creator hangs. Your application sucks the whole computation power until it crashes.
    You are comparing a double with an integer. The integer gots converted to a double, but because of the conversion both numbers are never the same and your break is never triggered.

    Probably something like the following may work

     while(true)
    {
             temp *= 10;
             n = temp;
             if( fabs ( temp -n) < 0.000001 )
                 break;
    }
    

  • Moderators

    A bit of description of the problem you are having you can find after the first headline Comparing for equality



  • We can't compare a double to an int. Anyways, I find the "break;" disturbing. I don't feel comfortable with it. I would try to remake this code.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.