命令行输入表达式求解计算器

参考自《Visula C++2013入门经典第七版》

从命令行输入表达式,然后分解识别各个符号间的数值,并进行相加减乘除,可支持小数点

// command_line_calculator.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <cstdlib>    //for exit()
#include <cctype>     //for isdigit()   对单字符的操作

using namespace std;
void eatspaces(char* str);
double expr(const char* str);
double term(const char* str, size_t& index);
double numble(const char* str, size_t& index);
const size_t MAX{ 80 };

int main()
{
	char buffer[MAX] = {};
	cout << endl
		<< "Welcome to your friendly calculation."
		<< endl
		<< "Enter an expression , or an empty line to quit"
		<< endl;
	for (;;)
	{
		cin.getline(buffer, sizeof buffer);
		eatspaces(buffer);
		if (!buffer[0])
			return 0;
		try
		{
			cout << "\t=" << expr(buffer) << endl << endl;
		
		}
		catch (const char* str)
		{
			cerr << str << endl;
			cerr << "Ending program. " << endl;
			return 1;
		
		}
	
	}
	system("pause");
    return 0;
}
//数组内复制移位,如果str【i】是空格,i就不会+1,只有j逐步+1
void eatspaces(char* str)
{
	size_t i = 0;
	size_t j = 0;
	while ((*(str + i) = *(str + j++))!= '\0')
	
		if (*(str + i) != ' ')
			i++;
	
	return;
}
//分析数
double number(const char* str, size_t& index)
{
	double value = 0;
	if (!isdigit(*(str + index)))
	{
		char message[31]= "INVALID character in number: ";
		strncat_s(message, str + index, 1);
		throw message;
	
	}
	while (isdigit(*(str + index)))
		value = 10 * value + (*(str + index++) - '0');
	if (*(str + index) != '.')
		return value;
	//以下为读取小数点后面的值 ,上面当数字后面的符号不是.就代表计算结束,返回value
	double factor = 1.0;
	while (isdigit(*(str + (++index))))   //因为。的原因,所以是 ++ index,判断出小数点区段的数字内容。
	{
		factor *= 0.1;
		value = value + (*(str + index) - '0')*factor;  //字符串中数字为ASCII码,转换成十进制需要减去‘\0’ (48)

	}
	return value;
}
double term(const char* str, size_t& index)
{
	double value = 0;
	value = number(str, index);
	while (true)
	{
		if (*(str + index) == '*')
			value *= number(str, ++index);	
		else if (*(str+index) == '/')
			value /= number(str, ++index);
		else
			break;
	}
return value;
}
//计算表达式值
double expr(const char *str)
{
	double value = 0;
	size_t index = 0;
	value = term(str, index);
	for (;;)
	{
		switch (*(str + index++))
		{
		case '\0':
			return value;
		case '+':
			value += term(str, index);
			break;
		case '-':
			value -= term(str, index);
			break;
		default:
			char message[38] = "Expression evalation error. Found: ";
			strncat_s(message, str + index - 1, 1);
			throw message;
			break;
		
		}
	
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值