/*******************************************************
Computer Programming - I
Warmup Problem Sheet - 1999-2000
*******************************************************/
/*
* Question:
* Write a program that takes a positive number with a fractional part
* and round it to two decimal places.
* For example, 32.4851 would round to 32.49 and 32.4431 would round to 32.44.
* Do not use the precision specifier of the control string in printf function.
*/
#include <stdio.h>
#define NUM_LENGTH 20
main()
{
char str[NUM_LENGTH];
int len,i=0,point_position=-1;
printf("Give the number: ");
scanf("%s",str);
len=strlen(str);
for(i=0;i<len;i++)
{
if((str[i]<'0'||str[i]>'9') && str[i]!='.')
{
printf("Error: This is not a floating point number\n");
exit(1);
}
if(str[i]=='.')
if(point_position>=0)
{
printf("Error: This is not a floating point number\n");
exit(1);
}
else
point_position=i;
}
for(i=len-1;i>point_position+2;i--)
if(str[i]>='5')
str[i-1]+=1;
// if(str[point_position+2]>'9')
// str[point_position+2]='9';
for(i=point_position+2;i>0;i--)
{
if(i==point_position)
continue;
if(str[i]>'9')
{
if(i-1==point_position)
str[i-2]+=1;
else
str[i-1]+=1;
str[i]-=10;
}
else
break;
}
if(str[0]>'9')
{
printf("1");
str[0]-=10;
}
str[point_position+3]='\0';
printf("%s\n",str);
}/* End of main*/