我在Microsoft Visual Studio 2012中構建一個應用程序,我有一個函數需要一個char數組,並且應該返回一個單精度浮點數。我將如何將字符數組轉換爲浮點數並檢查其範圍?
My功能:
Token aa_func08(char lexeme[]){
Token t; /* floating point literal Token to be returned */
double temp; /* floating point value of character array */
temp = atof(lexeme); /* convert character array to floating point value */
if ((FLT_MAX - temp <= FLT_EPSILON) || (temp - FLT_MIN <= FLT_EPSILON)) /* floating point value is outside the accepted range */
return aa_table[ES](lexeme); /* return an error Token */
t.code = FPL_T; /* set Token code */
t.attribute.flt_value = (float)temp; /* set Token integer value to floating point literal value */
return t; /* return floating point literal Token */
}
我想與最大和最小值用於浮點數據類型查詢的浮點值,並且我還需要檢查char數組的長度。
我期望的輸出如下:
如果我通過:
1.999999999999999911111111111111111111111111111111111111111111111111111111111111111
我期望能獲得:2.000000
如果我通過:
999999999999999999999999999999999999999999999999999999999999999999999999999999999.0
我期望得到:99999999999999999999
如果我通過:
0.00000000000000000000000000000000000000000000000000000000000000000000000000000000001
我期望能獲得:0.000000000000000000
有誰知道我能取得這樣的成績,或者至少指向我朝着正確的方向?謝謝!
EDIT
對於第一種情況,結果2.000000
由32位浮點表示。另外兩個結果只是字符串lexeme
被截斷爲前20個字符。因此,總而言之,如果lexeme
代表有效的float
,它表示爲浮點數,但如果lexeme
代表無效的float
(超出範圍,小數點後的缺失數字等),那麼lexeme
的前20個字符是我返回(不是實際的float
)。
什麼是'FLT_MAX'和'FLT_MIN'? – 2014-10-28 16:51:28
我會考慮看sscanf。還請查看[LOLCODE實現](https://github.com/justinmeza/lci/blob/master/tokenizer.c) – 2014-10-28 16:52:03
@代碼學徒他們是在float.h中定義的常量,用於最大和最小浮點數點值。 – 2014-10-28 16:58:42