How to limit the decimal places of the scanf of a double variable?

9

The exercise asks that the readings of double variables be limited to only one decimal place each. I tried to put "%.1lf" in scanf , just like we used in printf , but it did not work.

How could I solve this?

int main(int argc, char** argv) {


    double A, B, MEDIA;

    do{
          printf("Digite A: ");
          scanf("%lf", &A);

    }while(A<0 || A>10);

    do{
          printf("Digite B: ");
          scanf("%lf", &B);

    }while(B<0 || B>10);


    MEDIA=(A+B)/2;

    printf("MEDIA = %.5lf\n", MEDIA);

    return (EXIT_SUCCESS);
}
    
asked by anonymous 12.08.2016 / 05:55

1 answer

11

You can not do this. scanf() is useful for very basic readings. If you need something more complex you need to write a more sophisticated function or use some library that provides something better. In real applications it's common for programmers to have something at hand.

You can not even limit the amount of each decimal by using double since the representation of it is binary. It is possible to do some calculation (multiplies by 10, takes the whole part and divides by 10) to round values (but inaccurately ). This is not the same as limiting.

Another possibility is to work with integers, which makes typing a bit more difficult because if the note is 7.5 you would have to type 75, then resolve the comma in the presentation.

Could still read as text, convert to integer. This would make the user experience easier, but it would make development difficult. In a way it falls into the first alternative of doing a sophisticated function of reading data.

    
12.08.2016 / 06:14