I have a simple program that calculates the sum of a vector. Here is the implementation.
double sum(vector<double> v) {
double sum = 0;
for (size_t i = 0; i < v.size(); i++) {
sum += v[i];
}
return sum;
}
But when I test with decimal numbers, it doesn't seem to work.
void test_sum_decimal() {
cout << "test_sum_decimal" << endl;
vector<double> test = {1.2, 3, 6.5, 0.1};
cout << sum(test) << endl; // Prints 10.8
if (sum(test) == 10.8) {
cout << "EQUAL" << endl; // Doesn't print "EQUAL"
}
assert(sum(test) == 10.8); // Terminates program because expression is false
cout << "PASS!" << endl;
}
I have a feeling it is due to the datatype double not being 100% precise, but I do not know for sure.
Any help is appreciated. Thank you :)