Add horner_class.cpp

This commit is contained in:
2024-10-11 08:17:22 +02:00
parent 2dc6146b34
commit 53059c26b4

174
horner_class.cpp Normal file
View File

@@ -0,0 +1,174 @@
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
class Wielomian
{
public:
bool readFromFile(string filename)
{
string str;
stopien = 0;
fstream file(filename);
if (!file)
{
cerr << "Nie udalo sie otworzyc pliku o nazwie: " << filename << "\n";
exit(EXIT_FAILURE);
}
while (getline(file, str))
{
a.insert(a.begin(), stof(str));
stopien++;
}
file.close();
return true;
}
void setX(float x)
{
this->x = x;
}
bool oblicz()
{
b.resize(stopien);
for (int i = stopien - 1; i >= 0; i--)
{
if (i == stopien)
{
b[i] = a[i];
}
else if (i > 0)
{
b[i] = a[i] + b[i + 1] * x;
}
else if (i == 0)
{
b[i] = a[i] + b[i + 1] * x;
}
}
return true;
}
void wyswietl_wynik()
{
for (int i = b.size() - 1; i >= 0; i--)
{
cout << "b" << i << ": " << b[i] << "\n";
}
cout << "Rozwiazaniem wielomianu jest: " << b[0] << endl;
}
private:
vector<float> a;
vector<float> b;
int stopien;
float x;
};
int main()
{
float x = 0;
Wielomian wielomian;
cout << "Program do obliczenia wielomianu schematem hornera\n";
cout << "Podaj x dla ktorego szukamy rozwiazania: ";
cin >> x;
wielomian.readFromFile("dane.txt");
wielomian.setX(x);
wielomian.oblicz();
wielomian.wyswietl_wynik();
return 0;
}
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
class Wielomian
{
public:
bool readFromFile(string filename)
{
string str;
stopien = 0;
fstream file(filename);
if (!file)
{
cerr << "Nie udalo sie otworzyc pliku o nazwie: " << filename << "\n";
exit(EXIT_FAILURE);
}
while (getline(file, str))
{
a.insert(a.begin(), stof(str));
stopien++;
}
file.close();
return true;
}
void setX(float x)
{
this->x = x;
}
bool oblicz()
{
b.resize(stopien);
for (int i = stopien - 1; i >= 0; i--)
{
if (i == stopien)
{
b[i] = a[i];
}
else if (i > 0)
{
b[i] = a[i] + b[i + 1] * x;
}
else if (i == 0)
{
b[i] = a[i] + b[i + 1] * x;
}
}
return true;
}
void wyswietl_wynik()
{
for (int i = b.size() - 1; i >= 0; i--)
{
cout << "b" << i << ": " << b[i] << "\n";
}
cout << "Rozwiazaniem wielomianu jest: " << b[0] << endl;
}
private:
vector<float> a;
vector<float> b;
int stopien;
float x;
};
int main()
{
float x = 0;
Wielomian wielomian;
cout << "Program do obliczenia wielomianu schematem hornera\n";
cout << "Podaj x dla ktorego szukamy rozwiazania: ";
cin >> x;
wielomian.readFromFile("dane.txt");
wielomian.setX(x);
wielomian.oblicz();
wielomian.wyswietl_wynik();
return 0;
}