"A little progress everyday adds up to big results"

Monday 12 January 2015

C Programming: Let the user specify the number of decimal digits after the decimal point

                   In a C program, what will we do if we want to display only specific number of digits (which is determined at run time, like user input) after decimal point? We can get the number from the user, put it in switch() and provide a case for each individual number, as follows.


int num;
float pi = 3.1415
93;
printf ( "Enter the number of decimal digits to be shown: ");
scanf ( "%d", &num );
switch ( num )
{
case 1 : printf ( "%0.1f", pi ); break ;
case 2 : printf ( "%0.2f", pi ); break ;
...................
}

                    But, is it possible to give for each and every number? Moreover, this is not the correct way of programming. Use it in a single statement, instead of switch.


int num;
float pi = 3.141593;
printf ( "Enter the number of decimal digits to be shown: " );
scanf ( "%d", &num );
printf ( "%*.*f", 0, num, pi );
 
This will display 'num' digits after the decimal point. In the last statement, the first asterisk is replaced by 0 and the second asterisk by the value of 'num'.

Give full freedom to the user!

No comments:

Post a Comment