Created
November 26, 2009 07:18
-
-
Save shaobin0604/243299 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| * Exercise 5-2. Write getfloat, the floating-point analog of getint. What | |
| * type does getfloat return as its function value? | |
| */ | |
| #include <stdio.h> | |
| #include <ctype.h> | |
| int getch(void); | |
| void ungetch(int); | |
| /* getfloat: get the next floating-point number from input */ | |
| int getfloat(float *pn) | |
| { | |
| int c, sign; | |
| float power; | |
| while (isspace(c = getch())) /* skip white space */ | |
| ; | |
| if (!isdigit(c) && c != EOF && c != '+' && c != '-' && c != '.') | |
| { | |
| ungetch(c); | |
| return 0; | |
| } | |
| sign = (c == '-') ? -1 : 1; | |
| if (c == '+' || c == '-') | |
| c = getch(); | |
| for (*pn = 0.0; isdigit(c); c = getch()) | |
| *pn = *pn * 10 + (c - '0'); /* integer part */ | |
| if (c == '.') | |
| c = getch(); | |
| for (power = 1.0; isdigit(c); c = getch()) | |
| { | |
| *pn = *pn * 10.0 + (c - '0'); /* fraction part */ | |
| power *= 10; | |
| } | |
| *pn *= sign / power; /* final number */ | |
| if (c != EOF) | |
| ungetch(c); | |
| return c; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment