1

I am searching for a way to check if a certain variable holds an integer or no. My program asks the user for the values of a set of variable then it computes the variable k needed to make another variable e an integer. The code for calculating k is essentially a for loop that increments k from zero until it reaches a value making e an integer. But I can't figure out how to check that e is an integer. Here is the code I am thinking of:

for (int k = 0; k!=wk; k++) 
 { 
  e = (1+k*f_n)/d;
 if()
 }

The variable wk is just there so that when e is an integer, wk is to be equal to k, and so the loop ends.

5
  • 3
    @πάνταῥεῖ That question contains answers for the r language Commented Apr 29, 2014 at 21:00
  • 2
    @πάνταῥεῖ the other question isn't c++ Commented Apr 29, 2014 at 21:00
  • 1
    Compare the value of (int)e with e and make sure they are equal... Commented Apr 29, 2014 at 21:00
  • What was e declared as? Commented Apr 29, 2014 at 21:02
  • @gha.st Sorry, that was too quick voting! But I'm pretty sure there's an appropriate dupe for c++. Commented Apr 29, 2014 at 21:03

2 Answers 2

4

You don't want to check if e is an integer. You want to check if 1 + k*f_n is a multiple of d. Use the modulo operator for that.

if (((1 + k*f_n) % d) == 0)
Sign up to request clarification or add additional context in comments.

Comments

0

Assuming that e is a floating-point type,

int u = (int) e;
if (e > (float)u || e < (float)u)
  continue;
break;

This solution within the confines of what is otherwise modular arithmetic will suffer from rounding errors. Please consider using the modulus operator instead.

1 Comment

This approach is incomplete if e is negative.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.