Below is my code snippet which seemed to work fine but then I found the following problem:
When I type in 2.22 for example then the function returns 2.2200000000000002,
when I type in 6.66 then function returns 6.6600000000000001 !!!!
When I debug then it is clearly visible that:
input = "2.22"
but MyNumber = 2.2200000000000002
It seems that something goes wrong during myStream >> myNumber conversion.
Any idea how to solve this or what can be the problem???
Here is the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
double MyCin( string MyText )
{
// This function prints out the text in the parameter to the screen
// then gets a number and checks it, then returns the number
double myNumber = 0;
string input = "";
// Get a number safely.
while (true)
{
cout << MyText;
getline(cin, input);
// This code converts from string to number safely.
stringstream myStream(input);
if (myStream >> myNumber)
break;
cout << "Invalid number, please try again" << endl;
}
return myNumber;
};
This is how I call the function:
a1 = MyCin("Please input a1= ");
Thanks for the answers, I have found out to and all difficulties how to compare floating numbers:)
I know now that fmod(f1,f2) does not work always correctly:(
Any better way to calculate modulus of two floating number?
I know one way first to convert to integer then calculate modulus but any other good way?
fmod is working. It is just that the numbers that you pass to fmod isn't exactly 6.66 and 2.22. More precisely (but not exactly) 6.6600000000000001421 and 2.2200000000000001954. So to calculate f1 mod f2 we just subtract f2 from f1 until we get a value less than f2.
6.6600000000000001421 - 2.2200000000000001954 = 4.4399999999999999467
4.4399999999999999467 - 2.2200000000000001954 = 2.2199999999999997513
Now we stop because we have got a value less than f2.