K & R ex。 4.2要求您修改缺少指數處理機制來處理指數(如123e6或456e-7)的給定(非標準)atof函數。我添加了一個小改動來處理正確輸入的無空格的單位指數。爲了檢查它是否工作,我添加了樣本輸入數據和一個printf函數給main。返回值是完全關閉的(有些是零,沒有符號或小數,沒有明顯的關係)。有人可以幫我改進嗎?代碼:atof exercise(K&R第4.2節,練習4.2)
#include <ctype.h>
double antof(char[]); /* name changed to protect the innocent
and avoid references to stdlib functions */
int main()
{
char putin1[] = "12345";
char putin2[] = "987.65";
char putin3[] = " -2468";
char putin4[] = "12e2";
char putin5[] = " -34E-3";
printf ("%s \t %s \t %s \t %s \t %s \n\n", putin1, putin2, putin3, putin4, putin5);
double converted1 = antof(putin1);
double converted2 = antof(putin2);
double converted3 = antof(putin3);
double converted4 = antof(putin4);
double converted5 = antof(putin5);
printf ("%d \t %d \t %d \t %d \t %d", converted1, converted2, converted3, converted4, converted5);
return 0;
}
/* atof: convert string s to double */
double antof(char s[])
{
double val, power;
int i, sign;
for (i = 0; isspace(s[i]); i++) /* skip white space */
;
sign = (s[i] == '-') ? -1 : 1;
if (s[i] == '+' || s[i] == '-')
i++;
for (val = 0.0; isdigit(s[i]); i++)
val = 10.0 * val + (s[i] - '0');
if (s[i] == '.')
i++;
for (power = 1.0; isdigit(s[i]); i++) { /*tracks right side of decimal, keeps adding to val */
val = 10.0 * val + (s[i] - '0'); /* but keeps multiplying power by 10 to keep track of decimal place */
power *= 10;
}
/* added from here to handle scientific notation */
int exponenty;
int exponentysign;
if (s[i] == "e" || s[i] == "E")
i++;
if (s[i] == '-')
exponentysign == -1;
i++;
exponenty = (s[i] - '0');
/* full functionality would require storing data like val and power
but here I assume single digit exponent as given in the example */
if (exponentysign == -1)
exponenty = (1/exponenty);
return (sign * val/power) * (10^exponenty);
}
一如既往的感謝。
我們不是代碼審查。如果你的代碼是正確的並且工作正常,你可以在那裏嘗試。如果你有問題,請閱讀[問]並按照建議。也適當地格式化您的代碼。 – Olaf
@Olaf OP表示代碼無法正常工作,這將成爲Code Review的焦點話題。 – Phrancis