Sunday 12 July 2015

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<stdio.h>
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.


No comments:

Post a Comment