[luoguP1022] 计算器的改良(模拟)

字符串解析求解线性方程
本文介绍了一个使用C++编写的程序,该程序能够解析输入的字符串形式的线性方程,并通过简单的字符串处理和数学运算求解出未知数的值。代码实现了对手写线性方程表达式的解析,包括正负号、数字系数和未知数的识别。

传送门

 

超级大模拟。。

 

代码

#include <cstdio>
#include <cstring>
#include <iostream>
#define isword(x) ((x) >= 'a' && (x) <= 'z')

int n, a1, b1, a2, b2, f, x;
char s[1001], c;

int main()
{
	int i;
	scanf("%s", s + 1);
	n = strlen(s + 1);
	i = f = 1;
	while(i <= n)
	{
		if(!isdigit(s[i]))
		{
			if(isword(s[i]))
			{
				c = s[i];
				i++;
				continue;
			}
			if(isdigit(s[i - 1]) && i != 1) b1 += x * f;
			if(!isdigit(s[i - 1]) && i != 1)
			{
				if(!isdigit(s[i - 2])) a1 += f;
				else a1 += x * f;
			}
			if(s[i] == '+') f = 1;
			if(s[i] == '-') f = -1;
			if(s[i] == '=') break;
			i++;	
		}
		x = 0;
		while(isdigit(s[i])) x = (x << 1) + (x << 3) + s[i++] - '0';
	}
	i++;
	f = 1;
	while(i <= n)
	{
		if(!isdigit(s[i]))
		{
			if(isword(s[i]))
			{
				c = s[i];
				i++;
				continue;
			}
			if(isdigit(s[i - 1]) && s[i - 1] != '=') b2 += x * f;
			if(!isdigit(s[i - 1]) && s[i - 1] != '=')
			{
				if(!isdigit(s[i - 2])) a2 += f;
				else a2 += x * f;
			}
			if(s[i] == '+') f = 1;
			if(s[i] == '-') f = -1;
			i++;
		}
		x = 0;
		while(isdigit(s[i])) x = (x << 1) + (x << 3) + s[i++] - '0';
	}
	if(isdigit(s[i - 1])) b2 += x * f;
	if(!isdigit(s[i - 1]))
	{
		if(!isdigit(s[i - 2])) a2 += f;
		else a2 += x * f;
	}
	a1 -= a2;
	b2 -= b1;
	printf("%c=", c);
	if(b2 == 0) puts("0.000");
	else printf("%.3lf\n", double(b2) / double(a1));
	return 0;
}

  

转载于:https://www.cnblogs.com/zhenghaotian/p/7091485.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值