gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 16:19:12 24 4
gpt4 key购买 nike

#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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com