#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
float custom_atof(const char *str) {
// Your logic here
bool neg_falg = false;
//detect optional sign
if(*str=='-'){
neg_falg = true;
str++;
}
else if(*str=='+'){
str++;
}
//first detect integer part then fractional
bool fract_detect_flag = false;
float int_num =0;
float fract_num =0;
float fract_den =1;
while(*str!='\0'){
if(*str=='.'){
if(fract_detect_flag){
// TODO: handle double dots!
printf("Error: double dots!");
return 0.0;
}
fract_detect_flag = true;
str++;
}
if((*str>='0')&&(*str<='9')){
if (fract_detect_flag){
//parsing fractional part
fract_num = fract_num*10 + *str - '0';
fract_den = fract_den*10;
}
else{
// parsing integer part
int_num = int_num*10 + *str - '0';
}
}
else{
break;
}
str++;
}
float ret_val_f = int_num + fract_num/fract_den;
if(neg_falg){ ret_val_f = -ret_val_f; }
return ret_val_f;
}
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;
}
Input
123.45
Expected Output
123.45