[英]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.