C program to calculate no. of significant digits and rounding off the number if it is a floating number
#include<stdio.h>
#include<string.h>
using namespace std;
int main()
{
char s[200];
scanf("%s",&s);
int l,i,j,n,d,c=0;
l=strlen(s);
for(i=l-1;i>=0;--i)
{
if(s[i]!='0')break;
}
j=i;
for(i=0;s[i]!='.';++i)
{
if(s[i]!='0')break;
--j;
}
for(i=0;i<l;++i)
if(s[i]=='.')
c=1;
if(!c)
{
++j;
printf("Number of significant digits are %d",j);
goto end;
}
printf("Number of significant digits are %d \n How many Significant Digits you want(Should not be less than decimal place)?\n",j);
scanf("%d",&n);
d=j-n;
for(i=l-1;i>=0;--i)
if(s[i]!='0')
break;
else
s[i]='-';
while(d--)
{
if(s[i]=='.')
{
s[i]='-';
continue;
}
else if(s[i]>'5')
{
s[i-1]=char(int(s[i-1])+1);
s[i]='-';
}
else if(s[i]<'5')
{
s[i]='-';
}
else if(s[i]=='5')
{
if((int(s[i-1]))%2)
{
s[i]='-';
}
else
{
s[i-1]=char(int(s[i-1])+1);
s[i]='-';
}
}
--i;
}
for(i=0;i<l;++i)
if(s[i]!='-')
printf("%c",s[i]);
end:
return 0;
}
Good job.
ReplyDelete