简体   繁体   中英

How to find if a floating point is equal to an integer value in C++

I am fairly inexperienced in C++ and I am designing a program that requires integers, but the values that need to become integers can also be floats, it depends on the user's choice. I have not found anything on how to do these functions. Basically my code looks like this:

float a;
cin >> a;
switch (a) {
case 1:
    break;
case 2:    
    break;
default:
    break;
}

And I need to check if it is an integer before the switch statement. Please help.

您可以使用以下方法进行测试:

if( a == (int)a ) { /*is integer*/ } else { /*not an integer*/ }

一种可能的方法是使用use floor()函数,然后进行比较:

if(floor(a) == a) { .... }

This will get you close

if (std::round(a) == a) { ... }

The floating point representation can be slightly above or slightly below the actual number, so a better solution would be:

double EPSILON = 0.0000000001;
if (std::abs(std::round(a) - a) < EPSILON) { ... }

Where you set EPSILON to the desired precision of your floating point number (eg if you want it precise to 8 decimal places, you would set EPSILON = 0.00000001 ). This way, if the number is 4.999999999999934566 (very close to 5 ), you would see it as 5 . Additionally, if it is 5.000000000000000234 , you would still see it as 5 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM