I can print digits with putchar but how to print floats with put char?
Hello
So the function below can print any int using putchar. But I can't figure out how to print floats using putchar. Any ideas on this?
Regards!
Code:
void putDigit(int n){
int pow = 1;
char lastChar = ' ';
if (n < 0){
putchar('-');
lastChar = (char)((int)'0' + (n % 10));
n /= 10;
n *= (-1);
}
while (pow * 10 <= n)
pow *= 10;
while (pow != 0){
int d = n / pow;
putchar((char)((int)'0' + d));
n = n - d * pow;
pow /= 10;
}
if (lastChar != ' '){
putchar(lastChar);
}
}
floating value is not possible
you can print the integer values using your function. you cannot print the floating values.
because.
[%] modules operations are only allowed for integer. see in your code the following line
Code:
lastChar = (char)((int)'0' + (n % 10));
The negative number's is not possible your code.
================================================== ========================
you can handling the '.' dot in your code.
see the following code in this code I am handling [.] floating values
Code:
double atof(char s[])
{
double val, power;
int i, sign;
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.0;
//printf("val:%d",val);
}
return sign * val/ power;
}