How to limit reading decimals (scanf) of a double variable?

Asked

Viewed 4,004 times

9

The exercise asks the readings of the variables double are limited to only one decimal place each of them. I tried to put "%.1lf" in the scanf, as we used in the 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);
}
  • Did the answer solve your problem? Do you think you can accept it? If you don’t know how you do it, check out [tour]. This would help a lot to indicate that the solution was useful to you and to give an indication that there was a satisfactory solution. You can also vote on any question or answer you find useful on the entire site.

1 answer

11

There’s no way to do that. The 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 decimals using one double since his acting is binary. It is possible to do some calculation (multiply by 10, take the whole part and divide by 10) to round values (but inaccurate). That’s not the same as limiting.

Another possibility is to work with integers, which makes typing a little difficult because if the note is 7.5 it would have to type 75, then solve the comma in the presentation (in a way makes it easier because you no longer have to type the point, but it is less intuitive for the person, you have to make it clear that this is how you need to type, the person can take some getting used to, mainly because note 7 should be typed as 70 (you can validate to alert if the note is less than 10, unlikely the person to have this note and be typing error).

It could still read as text, convert to whole. This would facilitate the user experience, but would hinder development. Somehow falls into the first alternative of doing a sophisticated data reading function.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.