0

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.

3
  • Maybe something like a == (int) a? Commented Oct 31, 2013 at 19:47
  • if(a == ((int) a)) works. But you should create template functions once, and call either the function<int> either the function <float> in the code. Commented Oct 31, 2013 at 19:47
  • 2
    This sounds like an odd requirement. The input value apparently serves multiple roles: as a selector, and as something else that isn't shown here. That's an awkward design; it would be better to separate the two activities, and use an integer value as the selector. Commented Oct 31, 2013 at 19:50

3 Answers 3

1

You can test it with:

if( a == (int)a ) { /*is integer*/ } else { /*not an integer*/ }
Sign up to request clarification or add additional context in comments.

Comments

0

One possible approach is to use use floor() function and then compare:

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

3 Comments

std::floor will only work when the actual value is slightly above an integer. When it is slightly below, it would fall to the previous integer.
@ZacHowland : You are right, nevertheless, for the purpose of determining whether a float has no fractional part it is fine enough.
Not really. floor will work for 5.0000000001, but not for 4.999999999999995.
0

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 (e.g. 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.

2 Comments

(std::round(a) == (int)a) is true for 2.25 and false for 2.75; unless a is really big, the absolute difference between round(a) and (int)a will be either 1.0 or 0.0. I think you meant (std::abs(std::round(a) - a)) < EPSILON
@rici: Ah good catch. I actually meant std::round(a) == a. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.