[英]Converting string to float in C?
是的,所以在我的C程序中,我有一个从文件中获取浮点值的函数,在这里我试图做相反的事情,将字符串转换为浮点数。
float PsSc = atoi(stock01[DataCount].defPsSc);
我知道我的错误,我以为它适用于整数和浮点数,但事实并非如此。
我努力了
float PsSc = atof(stock01[DataCount].defPsSc);
那也不行。
因此,我的问题是:我可以用什么替换当前的代码行使其起作用?
输入:1.45。 预期输出:1.45,实际输出:1.00
编辑:
printf("\nYour previous speed was : %.2f Metres per Second",PsSc);
您正在寻找strtod()
函数族。
不仅将strtod()
输入字符串转换为double
(与strtof()
的float
和strtold()
为long double
),它也告诉你究竟在何处停止解析输入字符串(通过第二个参数)。
需要注意的是区域设置相关的或者是否strtod()
或atof()
期待一个小数点或小数逗号 ......
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <errno.h>
#include <stdio.h>
int main()
{
// play with "." vs. "," to see why this might be your problem
char * input = "1.45";
// will take a pointer beyond the last character parsed
char * end_ptr;
// strto...() might give an error
errno = 0;
// convert
float result = strtof( input, &end_ptr );
if ( errno == ERANGE )
{
// handle out-of-range error - result will be HUGE_VALF
puts( "out of range" );
}
if ( end_ptr != ( input + strlen( input ) ) )
{
// handle incomplete parse
printf( "Unparsed: '%s'\n", end_ptr );
}
printf( "result: %.2f\n", result );
return 0;
}
为什么我们不应该使用atof
成功时,atof()函数将转换后的浮点数作为双精度值返回。 如果无法执行有效的转换,则该函数将返回零(0.0)。 如果转换后的值超出可表示值范围的两倍,则将导致未定义的行为 。
相反,我们应该使用<stdlib.h>
存在的strtod()
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
char s[] = "1.45";
printf("Float value : %4.2f\n",strtod(s,NULL));
return 0;
}
它将正确打印1.45
请参阅此处的插图http://ideone.com/poalgY
尝试使用更具体的sscanf
:
参考: http : //www.cplusplus.com/reference/cstdio/sscanf/
float PsSc;
sscanf(stock01[DataCount].defPsSc, "%f", &PsSc);
范例: http : //ideone.com/BaPmDj
#include <stdio.h>
int main(void) {
char * str = "1.45";
float flt;
sscanf(str, "%f", &flt);
printf("value = %f\n", flt);
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.