题目:模仿函数getint的实现方法,编写一个读取浮点数的getfloat函数。getfloat函数的返回值应该是什么类型?
自我解答:
书本中getint的实现方法如下:
int getint(int *pn)
{
int c, sign;
while(isspace(c = getch()));
if(!isdigit(c) && c != EOF && c != '+' && c != '-')
{
ungetch(c);
return 0;
}
sign = (c == '-') ? -1 : 1;
if(c == '+' || c == '-')
c = getch();
for(*pn = 0; isdigit(c); c = getch())
*pn = 10 * *pn + c - '0';
*pn *= sign;
if(c != EOF)
ungetch(c);
return c;
}
读取浮点数需要支持出现小数点的情况,程序在处理时依然会先处理小数点前的部分,然后再加上小数点之后的数。程序如下:
int getfloat(float *pn)
{
int c, sign;
float power;
while(isspace(c = getch()));
if(!isdigit(c) && c != EOF