#C++/freelancer rates
8 messages · Page 1 of 1 (latest)
Hello mer, Would you please supply your code as text, so we have more information?
Increase your chance of getting help and look like a pro by sharing codeblocks not images. For example, you can type the following. Note, the ``` must be on their own line.
```
for number in range(10):
total += number;
```
Discord will render that as so:
for number in range(10):
total += number;
Click here to learn more about codeblocks: https://exercism.org/docs/community/being-a-good-community-member/writing-support-requests and http://bit.ly/howto-ask
so i resolved the issue, however i am not sure why this worked.
my original solution looked like this:
double apply_discount(double before_discount, double discount) {
return before_discount / 100.00 * (100 - discount);
}
the updated solution, looks like this (and all tests passed):
double apply_discount(double before_discount, double discount) {
return before_discount * (100 - discount) / 100.00;
}
maybe my question is why this change helped?
It could be a rounding issue
I believe it is a rounding error. I made this code to check:
#include <iostream>
#include <iomanip>
#include <limits>
int main() {
const double before = 140.0;
const double discount = 10;
const double opt1 = before / 100.00 * (100 - discount);
const double opt2 = before * (100 - discount) / 100.00;
const double target = 126.00;
// Print booleans as true/false
std::cout << std::boolalpha;
std::cout << "opt1 == opt2: " << (opt1 == opt2) << "\n";
std::cout << "opt1 == target: " << (opt1 == target) << "\n";
std::cout << "opt2 == target: " << (opt2 == target) << "\n";
// Print doubles with high precision and scientific notation
std::cout << std::setprecision(std::numeric_limits<double>::digits10 + 1) << std::scientific;
std::cout << "opt1: " << opt1 << "\n";
std::cout << "opt2: " << opt2 << "\n";
std::cout << "target: " << target << "\n";
}
The output is consistent with what we see when using gcc 13.2 x86-64:
opt1 == opt2: false
opt1 == target: false
opt2 == target: true
opt1: 1.2599999999999999e+02
opt2: 1.2600000000000000e+02
target: 1.2600000000000000e+02
Proof that it is a bad idea to test doubles for equality!
I used a matcher for one for the test cases with double, but not for the others. I will open an issue to correct that:
https://github.com/exercism/cpp/blob/b6b3993315dee5c163c38f1db24655e716c165e4/exercises/concept/freelancer-rates/freelancer_rates_test.cpp#L26C19-L26C64
That took a while, but there is a PR now. https://github.com/exercism/cpp/pull/936