c - 如何将字符串转换为 float ?

标签 c floating-point type-conversion atof strtod

#include<stdio.h>
#include<string.h>

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

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

我希望输出应该是 4.08000000 而我只有 4.00000000

有什么办法可以得到点后的数字吗?

最佳答案

使用 atof()strtof()* 代替:

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() 用于整数。
  • atof()/strtof() 用于 float 。

使用 atoll() 只能得到 4.00 的原因是因为它在找到第一个非数字时停止解析。

*请注意,strtof() 需要 C99 或 C++11。

关于c - 如何将字符串转换为 float ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7951019/

相关文章:

php - 如何将多维 PHP 数组转换为 XML?

reference - 在 Rust 中将 Vec<Box<Foo>> 转换为 &[&Foo]

c - 如何为 postgresql 创建一个返回两个或多个 OUT 参数的 C 语言函数?

c++ - 如何编写用于从 C 访问 C++ 类成员的包装器(具有继承和构造函数)

python - 为什么 (0.0006*100000)%10 是 10

c - 在c中添加浮点值

c# - 浮点运算稳定吗?

Python字节数组到位数组

c - 从文本文件的第一行读取整数数组,如果超过 10 则引发错误

c - 需要一些帮助,在 c 中使用定时器中断作为时钟