Hi. I have a problem whit the next code (an extract of a medical program) when I use 'if' and 'else if' statements. When the funtion f_cT is evaluated in the 'case 2' (line 41) of the 'switch' statment, and the user input the valor 4.14, for example, the variable p_cT is equal to -3, and this meaning that the condition for true in the 'if' statment (line 42) is violated, because 4.14 is not minus than 4.14 (obviously).
If you do the same with the value 160 in the 'case 1' (line 34) of the 'switch' statment, the condition of the analogous 'if' statment is respected.
Well, you see, floating point values are very annoying things.
Run this:
1 2 3 4 5 6 7 8
#include <iostream>
int main(){
float x=4.14f;
std::cout <<(x==4.14f)<<std::endl //note the f
<<(x==4.14)<<std::endl;
return 0;
}
General suggestion: don't make exact comparisons of floating point values if you can avoid it. In this case, if you only need precision up to hundredths, use 414 to mean 4.14 in code, and immediately multiply the user's input by 100 and truncate it.
A double has a larger range than that of float, meaning that double requires more resources to hold its range.
afrodriguezg wrote:
"a float with f" (sic)
The 'f' as in the suffix? If so, that suffix only serves as a denotation to indicate the type of the numerical value proceeding it. In this case, float. It allows the compiler to recognize the literal as a float type, not a double. This is the same story with: U, L, LL, UL, and ULL