this is a homework so were not supposed to use some commands which might make this hell of a lot easier. the users enters a decimal number and the programs stores it as an numerical string. im supposed to make it return the numerical string in float, hence, declaring the function a float. here's my code:
Code:
float toFloat(void)
{
float num = 0, dec = 0, temphold, ans;
double multiplier = 1;
char s[100];
int x = 0, counter = 0, stopper = 0;
printf("string? ");
scanf("%s", &s);
printf("\nYour string: %s", s);
for(x = 0;s[x] != '\0';x++)
{
if(s[x] == '.')
{
printf("\ndecimal piot detected");
x++;
for(x = x ; s[x] != '\0' ; x++)
{
multiplier = multiplier / 10;
temphold = s[x] - '0';
dec = dec + (temphold * multiplier);
printf("\nx: %c", s[x]);
printf("\ntemphold: %f", temphold);
printf("\nmultiplier: %f", multiplier);
printf("\ndec: %f", dec);
stopper = 1;
}
}
else if(stopper == 0)
{
counter++;
printf("\ncounter: %d", counter);
}
}
printf("\n\nDIVISION\n\n");
x = counter - 1;
multiplier = 1;
printf("\nx1: %d", x);
while(counter > 0)
{
temphold = (s[x] - '0');
printf("\ntemphold: %f", temphold);
num = num + (temphold * multiplier);
printf("\nmulti: %f", multiplier);
printf("\nx: %c", s[x]);
printf("\nnum: %f", num);
multiplier = multiplier * 10;
x--;
counter--;
}
ans = num + dec;
printf("\n\n%g", ans);
return ans;
}
my main problem is i cant seem to make it return the float value as it should. eg. input = 123.45, it should return 123.45, not 112347... another problem is that there are random really small numbers (eg. 0.00002) suddenly appearing, but i dont really mind those things. i used %g so that those numbers wont show up. im still a first year computer science student so there might be things that i dont know or stupid things i put in my code so dont be too harsh on me
you may also notice a lot of printfs there, im using it to trace my code, just to be sure.
thanks
ps. one of my friends told me that its impossible to return exactly 123.45, but he's also not sure