Correct my code as it is giving approximate float value but not exact
Code:
//code to convert string(containing digits) to equivalent float value
//Its giving approx value but not exact value
#include<stdio.h>
#include<ctype.h>
#include<math.h>
int main()
{
char a[20];
int c,i=0,k,sign=1;
float f=0;
while((c=getchar())!='\n' && i<19)
{
a[i]=c;
i++;
}
a[i]='\0';
for(i=0;a[i]==' ' && i<19;i++)
;
if( (a[i]=='+' && (sign=1)) || (a[i]=='-' && (sign=-1)) )
i++;
for(;a[i]!='\0'&&a[i]!='.';i++)
{
f=f*10+(a[i]-'0');
}
if(a[i]=='.')
for(k=-1,i++;a[i]!='\0';i++,k--)
f=f+pow(10,k)*(a[i]-'0');
f*=sign;
printf("\n num is %f",f);
return 0;
}
o/p:
123.654
num is 123.653999
See the following code it is giving exact answer compared to my answer
Code:
//concept took from K&R book
void main()
{
char s[]="123.654";
double val, power;
int i=0, sign,c;
for (i = 0; isspace(s[i]); i++) //skip white space
;
sign = (s[i] == '-') ? -1 : 1;
if (s[i] == '+' || s[i] == '-')
i++;
for (val = 0.0; isdigit(s[i]); i++)
val = 10.0 * val + (s[i] - '0');
if (s[i] == '.')
i++;
for (power = 1.0; isdigit(s[i]); i++) {
val = 10.0 * val + (s[i] - '0');
power *= 10;
}
printf("%f",sign*(val/power));
}
O/P:
123.654000