vendredi 6 novembre 2020

Floor bug in c++? [duplicate]

So I want to write 1 if the integer part is equal to the fractional part of the number. Assuming that I really want to use FLOOR function in c++.

#include<bits/stdc++.h>
using namespace std;

int main()
{
    double x;
    int y;
    cin>>x;
    y = floor(x);
    x = x - y;
    
    while(x!=floor(x))
        x = x*10;

    if(x == y)
        cout<<1;
    else
        cout<<2;
}

Where is the bug in the code? For 12.12 the result should be 1, but the code writes "2". I know that floor returns a double, so IDK if the problem is in while's condition. Don't jump with sth like "There are other solutions to this problem". I know there are, and I know how to solve it in other ways. Take it just as a curiosity. And please try to explain the reason why this happens.

Aucun commentaire:

Enregistrer un commentaire