100 Days of Code-day12

简单计算器程序。在每行中只能读取一个数,并累加求和。

//简单计算器,每次只能读取一个数
#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;
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值