Double type variable precision problem

Asked

Viewed 213 times

4

I’m solving the 1021 issue of the Judge URI, but I have a problem with the accuracy of my input value. Follow the base code:

#include <iostream.h>
int main(){
double a;
cin >> a;
}

The problem is that, if I insert for example 0.35 in the input, for some reason the variable a receives 0.349999, but I need this lost 0.001 to resolve the issue, what I can do to fix this?

  • 1

    If you need precision then do not use float or double variables because these data types are inherently inaccurate. If you effectively need to work with these types of data then considering an error will solve the problem, e.g. + or an error of 1E-5 (or 0.00001). For this particular problem you can use an integer data type and multiply the values by 100 to determine the amounts of banknotes and coins.

1 answer

2


The problem is in What is the correct way to use the float, double and decimal types?. Since you will not use a more suitable type in an exercise the solution is to equalize everything to integer, then the ideal is for the person to enter the amount of cents as an integer, but if the exercise requires entry as double The first thing you should do is equalize by multiplying by 100, then everything is treated with integer, it is even easier to resolve the issue. Take the die as double and multiplying does not guarantee that it will always be right, but it already avoids many mistakes, at least to pass the test. So the exercise is bad at encouraging inappropriate practices, which is why I say that trusting things on the internet is always a danger.

  • Thank you so much man, really multiply by 100 makes everything more quiet.

  • @Ricardocoutinho See on [tour] the best way to say thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.