将字符串转换为浮点数在C中? [英] Converting string to float in C?

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

问题描述

好吧,所以在我的C程序中,我有一个从文件中获取浮点值的函数,在这里我试图做相反的操作,将字符串转换为浮点数.

Right, So in my C program i have a function that takes a float value from file, and here i am trying to do the reverse, taking the string and turning it into a float.

 float PsSc = atoi(stock01[DataCount].defPsSc);

我知道我的错误,我以为它对整数和浮点数都适用,但事实并非如此.

I know my error, i assumed it would work for both integers and floats, it doesn't.

我尝试过

 float PsSc = atof(stock01[DataCount].defPsSc);

那也不起作用.

所以,我的问题是:我可以用什么替换当前的代码行使其起作用?

So, My question is: What can i replace my current line of code with to make it work?

输入:1.45.预期输出:1.45,实际输出:1.00

Input: 1.45 . Expected output: 1.45, Real output: 1.00

 printf("\nYour previous speed was : %.2f Metres per Second",PsSc);

推荐答案

为什么我们不应该使用atof

成功后,atof()函数将转换后的浮点数作为双精度值返回.如果无法执行有效的转换,则该函数将返回零(0.0).如果转换后的值超出可表示值范围的两倍,则会导致未定义行为.

On success, atof() function returns the converted floating point number as a double value. If no valid conversion could be performed, the function returns zero (0.0). If the converted value would be out of the range of representable values by a double, it causes undefined behavior.

相反,我们应该使用<stdlib.h>

#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

it will correctly prints 1.45

请参见此处的插图 http://ideone.com/poalgY

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

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