4.2 返回非整型值的函数
例子:
atoi和atof的实现(实现成了pzatoi和pzatof)
同时已经完成了Exercise 4-2 要求的对atof的扩充
#include<stdio.h> #include<ctype.h>
int pzatoi(char *s, int *pn){ int c, sign;
while((c = *s++) == ' ') ; if(!isdigit(c) && c != '+' && c != '-') return -1; sign = (c == '-') ? -1 : 1; if(c == '+' || c == '-') c = *s++; for(*pn = 0; isdigit(c); c = *s++) *pn = 10 * *pn + (c - '0'); *pn *= sign; return 0; }
double power(int a, int b){ int t = 1; if(b >= 0) for(; b > 0; b--) t *= a; else for(; b < 0; b++) t /= a; return t; }
int pzatof(char *s, double *pd){ int a, c, sign; double t;
while((c = *s++) == ' ') ; if(!isdigit(c) && c != '+' && c != '-' && c != '.') return -1; sign = (c == '-') ? -1 : 1; if(c == '+' || c == '-') c = *s++;
for(a = 0; isdigit(c); c = *s++) a = 10 * a + (c - '0'); *pd = a; if(c == '.'){ c = *s++; for(t = 0.1; isdigit(c); c = *s++){ *pd += t * (c - '0'); t *= 0.1; } } if(c == 'e'){ c = *s++; pzatoi(s, &a); *pd *= power(10, a); } *pd *= sign; return 0; }
int main(){ char s[50]; double a; scanf("%s", s); pzatof(s, &a); printf("%f\n", a); }
|
阅读(976) | 评论(0) | 转发(0) |