一個簡單計算器的C程序,該程序的功能: 每行讀取一個數(數前面可能有正負號) 並對他們求和, 每次輸完後把這些數的累加總和 打印出來(各種功能以後還會不斷地完善)。
- #include <stdio.h>
- #include <ctype.h>
- #define MAXLINE 100
- double atof(char s[]);
- int getline_(char s[], int lim);
-
- int main(void)
- {
- double sum;
- char line[MAXLINE];
-
- sum = 0;
- while (getline_(line, MAXLINE) > 0){
- printf("\t %g \n", sum += atof(line));
- }
- return 0;
- }
-
- double atof(char s[]) /*把字符串轉換為相應的雙精度浮點型*/
- {
- double val, power;
- int i, sign;
-
- for(i = 0; isspace(s[i]); i++) /*跳過空格*/
- ;
-
- 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++){ /*小數點左的處理*/
- val = 10.0 * val + (s[i] - '0'); /*字符轉 整數*/
- power *= 10.0;
- }
- return sign * val /power; /*把轉換好後的數返回*/
- }
-
- int getline_(char s[], int lim)
- {
- int c , i;
- i = 0;
- while(--lim > 0 && (c = getchar()) != EOF && c != '\n')
- s[i++] = c;
- if(c == '\n')
- s[i++] = c;
- s[i] = '\0';
- return i;
- }
-
-