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

The exercise asks that the readings of the variables double be limited to only one decimal place each. I tried putting "%.1lf" in scanf, just like we used in printf, but it didn't 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);
}
Author: Maniero, 2016-08-12

1 answers

There's no way to do that. 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 is common for programmers to have something like this at hand.

You can't even limit the number of decimal places using a double since its representation is binary. It is possible to do some calculation (multiply by 10, take the whole part and divide by 10) to round values (but without accuracy). This is not the same as limiting.

Another possibility is to work with integers, which makes it a little difficult to type because if the note is 7.5 you would have to Type 75, then solve the comma in the presentation (in a way it facilitates because you no longer have to type the point, but it is less intuitive for the person, you have to make it like 70 (can validate to alert if the note was less than 10, unlikely the person to have that note and be typo).

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

 11
Author: Maniero, 2020-02-17 15:58:15