Hanging when working with basic types in Qt
-
In a program, I want to display the number
0.12345as.12345(removing the first zero) in alineEdit. 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?
-
In a program, I want to display the number
0.12345as.12345(removing the first zero) in alineEdit. 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?
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; } -
A bit of description of the problem you are having you can find after the first headline Comparing for equality