Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<iostream>
- #include<conio.h>
- #include<string>
- bool ZnajdzWspolczynniki(std::string& sRownanie, float& fA, float& fB, float& fC)
- {
- int poz_A = -1, poz_B = -1;
- for (unsigned i = 0; i<sRownanie.length(); i++)
- {
- if (sRownanie.substr(i, 3) == "x^2") { poz_A = i; }
- else if (sRownanie.substr(i, 1) == "x") { poz_B = i; }
- }
- if (poz_A == -1) { std::cout<<"To nie jest rownanie kwadratowe!"; return false; }
- else
- {
- //A
- if (poz_A == 0) { fA = 1; }
- else
- {
- if ((sRownanie.substr(0,1) == "-") && poz_A -1 == 0) { fA = -1; }
- else { fA = stof(sRownanie.substr(0, poz_A)); }
- }
- //B
- if (poz_B == -1) { fB = 0; }
- else
- {
- if (sRownanie.substr(poz_A+3, 2) == "-x") { fB = -1; }
- else if (sRownanie.substr(poz_A+3, 2) == "+x") { fB = 1; }
- else { fB = stof(sRownanie.substr(poz_A+3,(poz_B-1)-poz_A)); }
- }
- //C
- if (sRownanie.substr(sRownanie.length()-3,1) != "x")
- {
- if (fB != 0) { fC = stof(sRownanie.substr(poz_B+1,(sRownanie.length()-3) - poz_B)); }
- else { fC = stof(sRownanie.substr(poz_A +3, sRownanie.length()-poz_A)); }
- }
- else { fC = 0; }
- return true;
- }
- }
- bool ZnajdzPierwiastki(float& fA, float& fB, float& fC, float& fX1, float& fX2)
- {
- int nDelta = (fB*fB) - (4*fA*fC);
- std::cout<<"Delta: "<<nDelta<<std::endl;
- if (nDelta < 0) { return false; }
- else if (nDelta == 0) { fX1 = -fB/(2*fA); fX2 = fX1; return true; }
- else { fX1 = (-fB+sqrt(nDelta))/(2*fA); fX2 = (-fB-sqrt(nDelta))/(2*fA); return true; }
- }
- int main()
- {
- std::string sRownanie;
- float fA, fB, fC, fX1, fX2;
- std::cout<<"Podaj rownanie kwadratowe do rozwiazania! [ ax^2+bx+c=0 ]"<<std::endl;
- std::cin>>sRownanie;
- if (sRownanie.substr(sRownanie.length()-2, 2) != "=0") { std::cout<<"Bledna forma rownania!"; }
- else
- {
- if(ZnajdzWspolczynniki(sRownanie, fA, fB, fC))
- {
- std::cout<<"A: "<<fA<<" B: "<<fB<<" C: "<<fC<<std::endl;
- if (!ZnajdzPierwiastki(fA, fB, fC, fX1, fX2))
- {
- std::cout<<"To rownanie nie ma pierwiastkow!";
- }
- else
- {
- std::cout<<"x1 = "<<fX1<<"\nX2 = "<<fX2;
- }
- }
- }
- _getch();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement