将String用户输入转换为double

我需要知道如何将用户输入(一个字符串)转换为double。 就像他在字符串“23.45”中写入一样,它会转换为双23.45( 没有任何库函数 )。

我已经得到了这个整数代码,但不知道如何继续使用double:

#include  void main() { char input[100]; printf("Type a String which will be converted to an Integer: "); scanf("%s", input); int number = 0; int i = 0; if (input[i] >= 48 && input[i] = '0' && input[i]  number %d \n", input, number); } else { printf("Enter a number! \n"); } } 

 #include  void main() { char input[100]; printf("Type a String which will be converted to a double: "); scanf("%s", input); double number = 0.0; double divider = 1.0; int inFraction = 0; int i = 0; if (input[i] >= 48 && input[i] <= 57) { inFraction = 0; while ((input[i] >= '0' && input[i] <= '9') || input[i] == '.') { if (input[i] == '.') { i++; inFraction = 1; continue; } number = number * 10.0; number = number + input[i] - '0'; i++; if (inFraction) divider *= 10.0; } number /= divider; printf("string %s -> number %g \n", input, number); } else { printf("Enter a number! \n"); } } 

你可能没有理由推出自己的版本,因为stdlib.h中的strtod已经涵盖了各种格式。

这是一个涵盖带符号数字作为输入的版本,并提供了一些可以放置更合适的error handling的提示:

 #include  static void halt_and_catch_fire (void); double strtod_homebrewn (const char* str) { double result = 0; // handle signs: bool is_negative = false; if(*str == '-') { is_negative = true; str++; } else if(*str == '+') { str++; } // handle the dot position: bool is_dot_found = false; double multiplier = 0.1; // the actual conversion: for(const char* s=str; *s!='\0'; s++) { if(*s >= '0' && *s <= '9') // ctype.h isdigit() would be preferred here { if(is_dot_found) { result += (*s - '0') * multiplier; multiplier /= 10; } else { result *= 10; result += *s - '0'; } } else if(*s == '.') { if(is_dot_found) // two dots? { halt_and_catch_fire(); // replace this with error handling } is_dot_found = true; } else if(*s != '\0') // all cases tested, some weird unknown character found { halt_and_catch_fire(); // replace this with error handling } } if(is_negative) { result = -result; } return result; } static void halt_and_catch_fire (void) { halt_and_catch_fire(); } 

编辑:正如clux指出的那样,当分数以零开始时,这会失败。 游民。 无论如何,也许有人设想了一个简单的解决方案? 我只能想到添加一个“readzeroes()”函数,让它在点之后运行。

你已经有了读取int的函数。 只需使用它。 伪代码:

 float read_float() { float f = read_int() if(next is dot) skipdot else return f; float frac = read_int() while (frac>1) frac /= 10 return f+frac; } 

编辑:仅对小数点后的小数位使用此方法。 阅读评论,了解为什么它会因大量数字而失败。

既然你提到没有使用任何库函数,你可以做这样的事情。

 float number; int decimal = 0; int decimal_found =10; while(input[i]!='\0') { if((input[i] <='0' || input[i] >='9')&&input[i]!='.' ) break; if(input[i] == '.') decimal = 1; if(decimal == 1) { number = number + (input[i] - '0')/decimal_found; decimal_found = decimal_found*10; } else { number = number *10; number = number + input[i] - '0'; } i++; } 

只需检查一个十进制变量,知道何时达到十进制,然后使用和if if为number变量设置单独的条件