Round-off in C (C++ too)

I think the best way to round off decimals in C for output would be to simply adjust the accuracy in the printf function. The following code demonstrates that-

#include

main()
{
float a = 3.56449;
printf(“\n%.2f”,a);
printf(“\n%.3f”,a);
printf(“\n%.4f”,a);
printf(“\n%.1f”,a);
printf(“\n%.0f”,a);
}
One thing though, you don’t get rolling round-offs, i.e, 3.56449 becomes 3.564 and not 3.565.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s