There is a problem with the float type.

Asked 2 years ago, Updated 2 years ago, 32 views

I was doing an atcoder, but if I type 1.3 and 1.2 in this cin, unwanted behavior (error output) will occur.I've tried various things like casts, but I don't know the cause.If anyone understands, please let me know.

#include<iostream>
using namespace std;

int main() {
    floaty;
    cin>>xy;
    float temp=(xy-(int)xy)*10;
    if((temp>=0)&&(temp<=2){
        cout<<temp<"-";
    }
    else if((temp>=3)&&(temp<=6){
        cout<<temp;

    }
    else if((temp>=7)&(temp<=9){
        cout<<temp<<"+";
    }
    else 
    cout<<"error";
    return 0;
}

c++

2022-09-30 16:22

2 Answers

The variable temp is of type float, so even if the calculation on the desk is 2.0, the expression in the computer may not match the integer 2.
Therefore, when specifying the range,

 if(temp>=0)&(temp<=2){
    cout<<temp<"-";
}
else if((temp>=3)&&(temp<=6){

Then all values between 2 and 3 will slip through.

 else if ((temp>2)&(temp<=6){

Let's say


2022-09-30 16:22

Use maximum accuracy to output floating-point values and see what you get.

#include<iostream>
# include <limits>
# include <iomanip>

int main() {
    using namespace std;
    
    cout<<setprecision(numeric_limits<float>:max_digits10);
    
    const floaty = 1.3f;
    cout<<(xy-(int)xy)*10)<<endl;
}

Most modern architectures use the IEEE-754 standard to represent floating-point types.

If the above code is executed and the architecture supports IEEE-754, the output will look like this:

// Program Output
2.99999952

As you can see, the condition (temp>=3)&(temp<=6) is false.

However, there is a way to fix this.

#include<iostream>
# include <cmath>

int main() {
    using namespace std;

    floaty;
    cin>>xy;

    // The following verifies that the floating-point number consists of a single decimal number.
    if(floor(xy*10)==xy*10){
        // roundf(...)" is used to round up the following floating-point values to eliminate accuracy errors.
        float temp=roundf(xy-(int)xy)*10);

        if(temp>=0&&temp<=2)
            cout<<temp<"-";
        else if (temp>=3&&temp<=6)
            cout<<temp;
        else if (temp>=7&&temp<=9)
            cout<<temp<<"+";
    }
    else 
        cout<<"error";
}

The above works correctly for program input 1.3 and gives 3 as expected.


2022-09-30 16:22

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.