TU-Programmieren_2/lab2/taskC.cpp
2025-04-09 10:22:44 +02:00

44 lines
1.1 KiB
C++

/// @file
/// @brief task C
/// g++ -std=c++20 taskC.cpp -o taskC && ./taskC
#include <iostream>
#include <valarray>
#include <vector>
/// @todo implement the class 'Polynomial' with the following properties:
/// - std::vector member variable to store the coefficients of the polynomial
/// - print(): prints the polynomial including the actual coefficients to the console
/// - overloaded '()' operator to evaluate polynomial at 'x'
class Polynomial {
public:
std::vector<double> coefficients;
void print() {
for (int i = 0; i < coefficients.size(); ++i) {
std::cout << coefficients[i] << "x^" << i;
if (i < coefficients.size() - 1) {
std::cout << " + ";
}
}
std::cout << std::endl;
}
double operator()(double x) {
double result = 0;
for (int i = 0; i < coefficients.size(); ++i) {
result += coefficients[i] * pow(x, i);
}
return result;
}
};
int main() {
/// @todo create an object from your class and use its member function and overloaded operator
Polynomial p;
p.coefficients = {1, 2, 3};
p.print();
std::cout << "p(2) = " << p(2) << std::endl;
return 0;
}