How to convert string to float?

前端 未结 8 1341
执念已碎
执念已碎 2020-11-27 03:21
#include
#include

int main() 
{
    char s[100] =\"4.0800\" ; 

    printf(\"float value : %4.8f\\n\" ,(float) atoll(s)); 
    return         


        
8条回答
  •  抹茶落季
    2020-11-27 04:12

    Use atof() or strtof()* instead:

    printf("float value : %4.8f\n" ,atof(s)); 
    printf("float value : %4.8f\n" ,strtof(s, NULL)); 
    

    http://www.cplusplus.com/reference/clibrary/cstdlib/atof/
    http://www.cplusplus.com/reference/cstdlib/strtof/

    • atoll() is meant for integers.
    • atof()/strtof() is for floats.

    The reason why you only get 4.00 with atoll() is because it stops parsing when it finds the first non-digit.

    *Note that strtof() requires C99 or C++11.

提交回复
热议问题