如何将字符串转换为浮点数? [英] How to convert string to float?

查看:36
本文介绍了如何将字符串转换为浮点数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include<stdio.h>#include<string.h>主函数(){字符 s[100] ="4.0800" ;printf("浮点值 : %4.8f
" ,(float) atoll(s));返回0;}

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

有没有办法得到点后面的数字?

解决方案

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

printf("浮点值 : %4.8f
" ,atof(s));printf("浮点值:%4.8f
" ,strtof(s, NULL));

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

  • atoll() 用于整数.
  • atof()/strtof() 用于浮点数.

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

*注意 strtof() 需要 C99 或 C++11.

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

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

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

I expect the output should be 4.08000000 whereas I got only 4.00000000.

Is there any way to get the numbers after the dot?

解决方案

Use atof() or strtof()* instead:

printf("float value : %4.8f
" ,atof(s)); 
printf("float value : %4.8f
" ,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.

这篇关于如何将字符串转换为浮点数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆