#C++/freelancer rates

8 messages · Page 1 of 1 (latest)

jaunty surge
#

Hi.

I am not sure what is wrong with my code. From my side the exercise is done, however when I run tests, I am getting error displayed on attached screenshot.

But if I am not wrong 126.0 == 126.0. Has anyone had similar issue?
Thanks!

ancient wing
#

Hello mer, Would you please supply your code as text, so we have more information?

random hearthBOT
jaunty surge
#

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?

clear bridge
#

It could be a rounding issue

next parcel
#

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!

ancient wing
ancient wing