Działająca wersja zrobiona na dwóch funkcjach

This commit is contained in:
2024-10-09 20:36:59 +02:00
parent 18ebbc0a2c
commit fa3a0894e2

View File

@@ -4,54 +4,38 @@
using namespace std; using namespace std;
int main() pair<vector<float>,int> read_data() {
{
int stopien = 0;
float x = 0;
string str; string str;
vector<float> a;
vector<string> temp; int stopien = 0;
cout << "Program do obliczenia wielomianu schemat hornera\n";
fstream file("dane.txt"); fstream file("dane.txt");
if (!file) if (!file)
{ {
cerr << "Nie udalo sie otworzyc plik\n"; cerr << "Nie udalo sie otworzyc pliku\n";
return -2; exit(EXIT_FAILURE);
} }
while (getline(file, str)) while (getline(file, str))
{ {
temp.push_back(str); a.insert(a.begin(), stof(str));
// cout << "a[" << stopien << "]=" << str << endl;
stopien++; stopien++;
} }
file.close(); file.close();
if (stopien <= 0) if (stopien <= 0)
{ {
cout << "Podano niepoprawny stopien!"; cout << "Plik istnieje, ale jest pusty!\n";
return -1; exit(EXIT_FAILURE);
} }
// cout << "stopien = " << stopien << endl; return make_pair(a, stopien);
vector<float> a(stopien); }
vector<float> policz(vector<float> a, int stopien, float x) {
vector<float> b(stopien); vector<float> b(stopien);
for (int i = stopien - 1, j = 0; i >= 0; i--, j++)
{
a[i] = stof(temp[j]);
// cout << "temp[" << i << "]=" << temp[j] << endl;
}
// for (int i = 0; i < a.size(); i++)
// {
// cout << "a[" << i << "]=" << a[i] << endl;
// }
cout << "Podaj x dla ktorego szukamy rozwiazania: ";
cin >> x;
for (int i = stopien - 1; i >= 0; i--) for (int i = stopien - 1; i >= 0; i--)
{ {
if (i == stopien) if (i == stopien)
@@ -66,10 +50,29 @@ int main()
{ {
b[i] = a[i] + b[i + 1] * x; b[i] = a[i] + b[i + 1] * x;
} }
// cout << i << endl;
} }
return b;
}
for (int i = 0; i < b.size(); i++) int main()
{
float x = 0;
cout << "Program do obliczenia wielomianu schematem hornera\n";
pair<vector<float>,int> para = read_data();
vector<float> a = para.first;
int stopien = para.second;
vector<float> b;
cout << "Podaj x dla ktorego szukamy rozwiazania: ";
cin >> x;
b = policz(a, stopien, x);
for (int i = b.size()-1; i >= 0; i--)
{ {
cout << "b" << i << ": " << b[i] << "\n"; cout << "b" << i << ": " << b[i] << "\n";
} }