C语言 如何将字符串转换为浮点数?

5sxhfpxr  于 5个月前  发布在  其他
关注(0)|答案(9)|浏览(67)
#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
有没有办法得到点后面的数字?

ao218c7q

ao218c7q1#

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

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

字符串
https://cplusplus.com/reference/cstdlib/atof/
https://cplusplus.com/reference/cstdlib/strtof/

  • atoll()表示整数。
  • atof()/strtof()用于浮点数。

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

  • 注意strtof()需要C99或C++11。
kxkpmulp

kxkpmulp2#

不幸的是,没有办法轻松做到这一点。每个解决方案都有其缺点。
1.直接使用atof()strtof():这是大多数人会告诉你做的,它在大多数时候都能工作。但是,如果程序设置了一个区域设置,或者它使用了一个设置区域设置的库,(例如,显示本地化菜单的图形库),并且用户将其区域设置为十进制分隔符不是.的语言(例如fr_FR,其中分隔符是,)这些函数将在.处停止解析,您仍然会得到4.0
1.使用atof()strtof(),但要更改区域设置;这是在调用atof()或类似的东西之前调用setlocale(LC_ALL|~LC_NUMERIC, "");的问题。setlocale的问题是它对进程是全局的,您可能会干扰程序的其余部分。请注意,您可能会使用setlocale()查询当前区域设置,并在完成后恢复它。
1.编写自己的浮点数解析例程。如果你不需要像指数解析或十六进制浮点数这样的高级特性,这可能会非常快。
另外,请注意,值4.08不能精确地表示为浮点数;您将获得的实际值是4.0799999237060546875

zfciruhq

zfciruhq3#

为什么不能使用atof()函数将string转换为double?

成功后,atof()函数将转换后的浮点数作为double值返回。如果无法执行有效转换,则函数返回零(0.0)。如果转换后的值超出了double可表示的值范围,则会导致 * 未定义行为 *。
参考:http://www.cplusplus.com/reference/cstdlib/atof/

使用函数strtod(),它更健壮。

试试这个代码:

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
    char s[100] = "4.0800";
    printf("Float value : %4.8f\n",strtod(s,NULL));
    return 0;
}

字符串
您将得到以下输出:
第一个月

mzaanser

mzaanser4#

使用atof()
但这是不推荐的,使用这个代替:

const char* flt = "4.0800";
float f;
sscanf(flt, "%f", &f);

字符串
http://www.cplusplus.com/reference/clibrary/cstdlib/atof/
atof()返回0的失败和转换0.0,最好不要使用它。

tcbh2hod

tcbh2hod5#

通过使用sscanf,我们可以将string转换为float。

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

int main() 
{
    char str[100] ="4.0800" ;     
    const char s[2] = "-";   
    char *token;
    double x;
   /* get the first token */ 
   token = strtok(str, s);
   sscanf(token,"%f",&x);
    printf( " %f",x );

    return 0; 
}

字符串

pbgvytdp

pbgvytdp6#

**提醒:**使用atof()时,请确保字符串中没有“”。atof(“1.123”)将返回0.000或类似的值。
解决方案

str_val[0] = "0";
str_val[len-1] = "\n"; //len = length of string

字符串

5anewei6

5anewei68#

double x;

char *s;

s = " -2309.12E-15";

x = atof(s);     /* x = -2309.12E-15 */

printf("x = %4.4f\n",x);

字符串

zbdgwd5y

zbdgwd5y9#

Main()  {
    float rmvivek,arni,csc;
    char *c="1234.00";
    csc=atof(c);
    csc+=55;
    printf("the value is %f",csc);
}

字符串

相关问题