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.

Mohamed Ahmed
  • 457
  • 1
  • 7
  • 25

2 Answers2

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)
David Schwartz
  • 179,497
  • 17
  • 214
  • 278
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.

abiessu
  • 1,907
  • 1
  • 18
  • 16