#include <stdio.h>
#include <stdint.h>
float custom_atof(const char *str) {
// Your logic here
int i, center=0, left=0, right=0, sign=0;
// look for a sign and for th edecimal point and for the end
char *ptr;
float result, multiplier;
if (*str == '+') {
sign = 1;
left = 1;
}
else if (*str == '-') {
sign = -1;
left =1;
}
// look for the decimal point and the end
i=0;
center= -1;
while (str[i] != '\0') {
if (str[i] == '.') {
center = i;
}
i++;
}
right = i;
if (center == -1) {
center = right;
}
//printf("sign: %d, left:%d, center:%d, right:%d\n", sign, left, center, right);
result = 0.0;
multiplier = 1.0;
for (i=(center-1); i >= left; i-- ) {
result += (str[i] - '0') * multiplier;
multiplier *= 10.0;
}
multiplier = 0.1;
for (i=(center+1); i < right; i++) {
result += (str[i] -'0') * multiplier;
multiplier *= 0.1;
}
if (sign == -1)
result *= -1.0;
return result;
}
int main() {
char str[101];
fgets(str, sizeof(str), stdin);
// Remove newline
uint8_t i = 0;
while (str[i]) {
if (str[i] == '\n') {
str[i] = '\0';
break;
}
i++;
}
float value = custom_atof(str);
printf("%.2f", value);
return 0;
}
use counters to scan for sign decimal point and end of string
if decimal point found, use it as the anchor (center), otherwise use the end of string as anchor
then scan left with multiplier by 10 for every iteration
and scan right of anchor (if anchor is not end of string) and multiplier by 0.1 every iteration
then account for the sign
Input
123.45
Expected Output
123.45