Domanda

I have a question - it may seem stupid to most, but i'm still a novice coder. How does one round a floating variable to display upto only 2 or 3 digits of precision ? thanks in advance

È stato utile?

Soluzione

Use the format specifier %.2f for 2 digits of precision. Similarly use %.3f for 3 digits. For future reference, here are the printf format specifiers.

#include <stdio.h>

int main()
{
    printf("%.2f\n", 0.005); // prints 0.01
    printf("%.2f\n", 0.004); // prints 0.00
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top