简单计算器程序。在每行中只能读取一个数,并累加求和。
//简单计算器,每次只能读取一个数
#define MaxLine 1000
double atof(char []);
int getline(char [], int);
int main()
{
char line[MaxLine];
double sum;
sum = 0.0;
while (getline(line, MaxLine) > 0)
{
printf("%g", sum += atof(line));
}
return 0;
}
//convert string s to double
double atof(char s[])
{
int i, sign, exp;
double value, power;
for (i = 0; isspace(s[i]); i++)//skip white space
;
sign = (s[i] == '-') ? -1 : 1;//keep track of sign
if (s[i] == '+' || s[i] == '-')
i++;
for (value = 0.0; isdigit(s[i]); i++)//get each character inputed and
//multiply its positive number by 10.0
//store the output by using a varible called value
{
value = value * 10.0 + s[i] - '0';
}
if (s[i] == '.') i++;
//since it's float,for each decimal we store the power value as multiples of 10
//using "value / power",we can get the final.then multiply it by the stored sign
//finally return the result
for (power = 1.0; isdigit(s[i]); i++)
{
value = value * 10.0 + s[i] - '0';
power *= 10.0;
}
value = sign * value / power;
if (s[i] == 'e' || s[i] == 'E')
{
sign = (s[++i] == '-') ? -1 : 1;
if (s[i] == '-' || s[i] == '+')
i++;
for (exp = 0; isdigit(s[i]); i++)
exp = exp * 10 + (s[i] - '0');
if (sign == 1)
{
while (exp-- > 0)
value *= 10;
}
else
{
while (exp-- > 0)
value /= 10;
}
}
return value;
}
//read a line into string s and return the length of line
int getline(char s[], int lim)
{
int i = 0;
char c;
//'='的优先级低于'&&'
//用--lim > 0代替i<lim-1 系统此时不用将两个变量i与lim进行比较
//只需要比较变量lim与常量0
while (--lim > 0 && (c = getchar()) != EOF && c != '\n')
{
s[i++] = c;
}
if (c = '\n')
{
s[i++] = c;
//用s[i++] = c代替了s[i]=c; i++;这样更为简便
}
s[i] = '\0';
return i;
}