-2

Hello and sorry if this question has been asked before, but I'm working on the Josephus problem and this is the code that I´ve written.

#include<stdio.h>
#include<cs50.h>
#include<math.h>

int main(void)

{
    printf("Number of people: ");
    float f=GetFloat();
    const int a=pow(2,floor(log(f)/log(2)));
    float c= 2*(f-2^a)+1;
    printf("%f\n", c);

}

When I try to compile it it gives me this error message.

clang -ggdb3 -O0 -std=c99 -Wall -Werror    Josephus.c  -lcs50 -lm -o Josephus
Josephus.c:11:20: error: invalid operands to binary
      expression ('float' and 'float')
    float c= 2*(f-2^a)+1;
                ~~~^~

The equation I'm trying to write in the code is c = 2(f – 2^a) + 1 Where "c" is the number I'm looking for, "f" is the number of people and "a" is the largets power of 2 smaller than f.

Sorry for any and all grammatical mistakes and my lack of knowledge of the topic, I'm new to programming. Cheers!

  • 1
    related/dupe of http://stackoverflow.com/questions/4843304/why-is-my-power-operator-not-working and http://stackoverflow.com/questions/845912/what-is-the-c-function-to-raise-a-number-to-a-power – NathanOliver Nov 08 '16 at 16:22

1 Answers1

0

Your problem is f-2^a. You probably expect this to subtract two to the power a from f. Trouble is ^ is the XOR operator, and it is lower precedence than subtraction. The compiler is treating this as (f-2) xor a. The LHS of the xor is float, so the a is being promoted to float ... and xor doesn't work with floats!

The fix is either:

f - pow(2.0, a)

or:

f - (1u << a)

(but only use the latter if you are confident that a is in range.

  • This really helped, in the end I changhed a couple of things, it works and give the actual answer to the problem! – carlos1106 Nov 08 '16 at 16:33