C 語言類問題

今天在使用標準庫函數atof時遇到以下問題:

不管atof(x)的內容x是什麼,轉換出來的的數總是0.000

如下兩段程序

Code1

#include #include int main(void){ char *temp = "074.2030"; printf("%.4f\r\n",atof(temp)); return 1;}

Code2

#include int main(void) { char *temp = "074.2030"; printf("%.4f\r\n",atof(temp)); return 1; }

這兩段的運行結果是不一樣的,如下所示

./Code174.2030./Code20.0000

造成這種情況的原因就是Code2沒有包含頭文件stdlib.h,在編譯時沒有報錯,但是會有一個warning,如下

warning: format ‘%f’ expects argument of type ‘double’, but argument 2 has type ‘int’ [-Wformat=] printf("%.4f\r\n",atof(temp));

如上,在沒有包含頭文件時,atof的結果是被當做int型處理的,所以造成了最後的轉換結果不正確,這種情況對atoi沒有影響,所以在使用庫函數時要查明對應的聲明頭文件,否則會造成意想不到的錯誤。

查看原文 >>
相關文章