factors of 2 code

I keep getting a compiler error saying "invalid operands of types . . ."
I'm trying to get the program to return the value of how many factors of 2 are in 12 (later this will be changed to an input number).
Thanks for any help.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cmath>

using namespace std;

int main() {

  for(int i=0; i < RAND_MAX; i++) {
    if((12/pow(2, i)) % 2 != 0) {
      cout << "twos = " << i << endl;
      break;
    }
  }

return 0;

}
The error is more than likely on line 11. You can not use the modulus operator on floating-point numbers. It is used for integers only. If you wish to get the remainder after division for floating-point you must use fmod[1]. Keep in mind though if you do this you may want to range to compare since you shouldn't compare floating-points like that. Floating-points are stored much differently than integers.
http://www.cplusplus.com/reference/cmath/fmod/
Thanks. I was able to fix it. I didn't realize that the pow function returns floating-point numbers.
Another way would be to cast the double to an integer

1
2
3
static_cast<int>( pow( 2 , i  );
//or
(int) pow( 2 , i );
Topic archived. No new replies allowed.