Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <cstring> /// strlen,strcpy
- #include <cmath> /// sqrt
- #include <cstdlib> /// atoi
- using namespace std;
- /// determinam coeficientul (de tip int) din sirul initial (de tip char*)
- /// verificare=1 se foloseste la a si b, unde sirInitial poate contine doar '+' (sau nu contine nimic) pentru 1 si '-' pentru -1
- int determinare(char sirInitial[],int verificare=1)
- {
- int lungime=strlen(sirInitial);
- if(verificare)
- {
- if(lungime==0)
- return 1;
- if(lungime==1&&sirInitial[0]=='-')
- return -1;
- }
- if(lungime==1&&sirInitial[0]=='+')
- return 1;
- return atoi(sirInitial);
- }
- /// -x-x^2
- void separare(char ecuatie[],int &a,int &b,int &c) /// atribuim variabilelor a,b,c, valorile aferente
- {
- int lungime=strlen(ecuatie),lungimeCoeficient,pozitie=0;
- char coeficient[10],coeficienti[3][10]; /// coeficienti[0] -> a, coeficient[1] -> b, coeficienti[2] -> c
- while(pozitie<lungime)
- {
- lungimeCoeficient=0;
- while(!isalpha(ecuatie[pozitie])&&pozitie<lungime)
- {
- if(ecuatie[pozitie+1]=='+'||ecuatie[pozitie+1]=='-'||pozitie==lungime-1)
- {
- coeficient[lungimeCoeficient++]=ecuatie[pozitie++],--pozitie;
- break;
- }
- coeficient[lungimeCoeficient++]=ecuatie[pozitie++];
- }
- coeficient[lungimeCoeficient]='\0';
- ///cout<<endl<<"Coef= "<<coeficient<<" POZ = "<<pozitie<<" URM CAR = "<<ecuatie[pozitie]<<endl;
- if(ecuatie[pozitie+1]=='^'&&ecuatie[pozitie+2]=='2') /// este a
- {
- strcpy(coeficienti[0],coeficient);
- pozitie +=2;
- }
- else
- if(isalpha(ecuatie[pozitie])) /// este b
- {
- strcpy(coeficienti[1],coeficient);
- ///++pozitie;
- }
- else /// este c
- if(ecuatie[pozitie+1]=='-'||ecuatie[pozitie+1]=='+'||pozitie<lungime)
- {
- strcpy(coeficienti[2],coeficient);
- }
- ++pozitie;
- }
- ///cout<<coeficienti[0]<<' '<<coeficienti[1]<<' '<<coeficienti[2]<<endl;
- a=determinare(coeficienti[0]);
- b=determinare(coeficienti[1]);
- c=determinare(coeficienti[2],0);
- ///cout<<a<<' '<<b<<' '<<c<<endl;
- }
- int main(void)
- {
- char ecuatie[100];
- int a=0,b=0,c=0;
- cin.get(ecuatie,100);
- separare(ecuatie,a,b,c);
- double x1,x2; /// Solutiile ecuatiei
- int delta=b*b-4*a*c;
- if(delta<0 ) /// Solutii imaginare
- cout<<"imaginare\n"<<(double)-b/(2*a)<<' '<<(double)sqrt(-delta)/(2*a)<<'i'; /// ecuatia are solutii imaginare
- else
- if(delta==0) /// Ecuatia are o singura solutie
- cout<<"real\n"<<(double)-b/(2*a);
- else /// Ecuatia are doua solutii -> o afisam pe cea mai mica, urmata de cea mai mare
- {
- double radDelta=sqrt(delta);
- x1=(-b+radDelta)/(2*a);
- x2=(-b-radDelta)/(2*a);
- if(x1>x2)
- swap(x1,x2);
- cout<<"reale\n"<<x1<<' '<<x2;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement