0
Hello! I’m doing a job for college and one of the parts I have to do is take the value of h and see if it’s positive and between 0.8 and 1.2. It’s very simple, but when I type 0.8, it accepts!! Could someone help me? please. Another thing, when they say 'between', the numbers that were used to measure from which to which number to pick, also enter (0.8, 1.2)?
float h;
do{
printf("Por favor, digite o tamanho do nivel em cm (entre 0.8 e 1.2): \n");
scanf("%f",&h);
if(h<0){
printf("Favor, insira um valor positivo!\n");
}
}while(!(h>0&&(h>0.8&&h<1.2)));
Wouldn’t it be simpler to just do it
while (h<0.8 || h>1.2)))
since, from what I understand you want a number in the interval[0.8, 1.2]
?– anonimo
Unfortunately it did not work :(. For some reason when I implement what you mentioned, the code does not accept 1.2 and accepts 0.8 (the strange thing here would be that it accepts 0.8). I have tried to put up to >= and <= for 0.8 and 1.2, but for some reason 1.2 will not :(
– VictorHugo22
This is the problem of the inherent inaccuracy of the representation of floating point numbers. Look at this test: https://ideone.com/G7e4Xo you will find that 1.2 is not accurately represented.
– anonimo
@anonimo, I took the liberty of making a Fork of your code. Using literals floating point error the same accuracy on both sides and the comparison works as expected (https://ideone.com/zMadkX). The problem in the case is the comparison of the type
float
on the one hand, with literals of the kinddouble
of the other.– Anthony Accioly
@Anthony Accioly: perfect. This is an aspect totally neglected by beginners (especially if it involves arithmetic operations). If defining
h
asdouble
will also obtain the expected result.– anonimo