分享一个大牛的人工智能教程。零基础!通俗易懂!风趣幽默!希望你也加入到人工智能的队伍中来!请点击http://www.captainbed.net
/*
* GetFloat: The floating-point analog of GetInt.
*
* GetFloat.c - by FreeMan
*/
#include <stdio.h>
#include <ctype.h>
#include <math.h>
#define BUFFERLENGTH 100
int GetCh(void);
void UngetCh(int);
int buf[BUFFERLENGTH];
int nfp = 0;
void ViewBuffer(void)
{
int i;
printf("\nbuffer:\n");
for (i = nfp - 1; i >= 0; i--)
{
printf("%d\n", buf[i]);
}
}
int GetCh(void)
{
return (nfp > 0) ? buf[--nfp] : getchar();
}
void UngetCh(int c)
{
if (nfp < BUFFERLENGTH)
{
buf[nfp++] = c;
}
else
{
printf("error: ungetch buffer overflow\n");
}
}
int GetFloat(float *pn)
{
int c, i, sign;
while (isspace(c = getchar()))
;
if (!isdigit(c) && c != EOF && c != '+' && c != '-')
{
UngetCh(c);
return 0;
}
sign = (c == '-') ? -1 : 1;
if (c == '+' || c == '-')
{
c = GetCh();
if (!isdigit(c))
{
UngetCh(sign == -1 ? '-' : '+');
return 0;
}
}
for (*pn = 0; isdigit(c); c = getch())
{
*pn = *pn * 10 + (c - '0');
}
if (c == '.')
{
c = GetCh();
for (i = 1; isdigit(c); c = GetCh(), i++)
{
*pn += (c - '0') / pow(10, i);
}
}
*pn *= sign;
if (c != EOF)
{
UngetCh(c);
}
return c;
}
int main()
{
int retval;
float x, *px;
px = &x;
retval = GetFloat(px);
printf("retval = %d, x = %.3f\n", retval, x);
ViewBuffer();
return 0;
}
// Input:
/*
-123.456
*/
// Output:
/*
retval = 10, x = -123.456
buffer:
10
*/