Luo Gu P1022 calculator improvement (analog)

Topic background

NCL is a specialized calculator improvement and upgrading of the laboratory, the lab recently received a task entrusted to a company: the need to add solving a linear equation functions on a particular model of the company's calculator. This laboratory will be the task to a novice just entering the Mr. ZL.

Title Description

In order to accomplish this task well, Mr. ZL first studied a number of instances of one dollar equation:

4 + 3x = 8

6a-5 + 1 = 2-2a

−5+12y=0

Mr. ZL defendant competent, typing on a calculator one dollar equation only contains an integer, and lowercase letters +, -, = three mathematical symbols (of course, the symbol "-" not only for the minus sign, also can be used as a negative number). Equation and no parentheses, no other numbers, letters unknowns in the equation.

You can assume the correctness of the judgment of the type of equation is done by another programmer, or that can be considered a linear equation typing are legitimate, and there is the only real solution.

Input Format

A one dollar equation.

Output Format

Results (After accurate to three decimal places) solution of the equation.
Sample input and output

Input 1

6a-5 + 1 = 2-2a

Output 1

a=0.750

Let us recall how former solution of the equation ...
polynomial fit the problem reduces to ax = b form, and finally b \ a is the answer
then is to simulate polynomial merger, the left side of the equal sign of the constant term to change sign, unknown coefficient number becomes equal right to be defined to simulate this process two flag to OK.
Also note

  • Because the value of -1/0 accuracy problems will be written -0.000, need special sentenced ...
  • Unknowns coefficient is 1 or -1, or there may be a write -a.

ACCODE

#include <iostream>
#include <cstdio>
using namespace std;
int flag1=1;
int flag2=-1;
string s;
double getnum(int &i)
{
	double ans=0;
	for(;i<s.size();i++)
	{
		if(s[i]>='0'&&s[i]<='9')
		{
			ans*=10;
			ans+=(s[i]-'0');
		}
		else
		break;
	}
	return ans;
}

char getk()
{
	for(int i=0;i<s.size();i++)
	{
		if(s[i]>='a'&&s[i]<='z')
		return s[i];
	}
}
int main()
{
	getline(cin,s);
	s+=' ';
	double a=0;
	double b=0;
	char k=getk();
	for(int i=0;i<s.size();i++)
	{
		if(s[i]=='=')
		{
			flag1*=-1;
			flag2*=-1;
		}
		else if(s[i]>='0'&&s[i]<'9')
		{
			double num;
			if(i==0||s[i-1]=='+'||s[i-1]=='=')
			num=getnum(i);
			else
			num=-1*getnum(i);
//			cout<<num<<endl;
			if(i!=s.size()&&s[i]==k)
			a+=(flag1*num);
			else
			{
				b+=(flag2*num);
				i--;
			}
		}
		else if(s[i]==k)
		{
			if(i==0||s[i-1]=='+'||s[i-1]=='=')
			a+=flag1;
			else
			a+=(-flag1);
		}
	}
	if(b/a==0)
	printf("%c=0.000",k);
	else
	printf("%c=%.3f",k,b/a);
	return 0;
}

Write it ugly

Published 30 original articles · won praise 9 · views 1313

Guess you like

Origin blog.csdn.net/Zhang_sir00/article/details/100165732