polynom
Feb 9, 2016 at 11:31am UTC
i don't know what's wrong with my code.
it is supposed to calculate a polynome but the result it's always 0
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
#include <iostream>
#include <vector>
using namespace std;
double power(double a, unsigned int n) {
double res = 0.;
for (unsigned int i = 0; i<n; i++)
res = res*a;
return res;
}
double evalpoly(vector<double > pol, double x) {
double res = 0.;
for (unsigned int i = 1; i <= pol.size(); i++)
res = res + pol[i]*power(x, i);
return res;
}
int main() {
vector<double > pol = {1.5, 2.5, 2.5, 4.0};
vector<double > vals = {0, 1, 1.5, 2};
for (unsigned int i = 0; i < vals.size(); i++)
cout << "P(" << vals[i] << ") = " << evalpoly(pol, vals[i]) << endl;
return 0;
}
Feb 9, 2016 at 11:39am UTC
look at lines 7 and 9. What happens when multiplying by zero?
At line 15
for (unsigned int i = 1; i <= pol.size(); i++)
the loop skips the first element of
pol, and then tries to access an out of range element one position past the end of the vector.
Topic archived. No new replies allowed.