Home > Software design >  C Trouble with operators [closed]
C Trouble with operators [closed]

Time:10-06

I was trying to do some operations with a n number. This is the code:

#include <stdio.h>

int main() {
    float n;

    printf("Enter a number:\n");
    scanf("%f",&n);
    printf("n^2 = %f\n",(n^2.0));
    printf("n^3 = %f\n",(n^3.0));
    printf("2^n = %f\n",(2.0^n));
    printf("3^n = %f\n",(3.0^n));

}

But when compiling it gives me an error. This is:

exercice14.c:10:23: error: invalid operands to binary expression ('float' and 'double')
printf("n^2 = %f\n",(n^2.0));
                     ~^~~~
exercice14.c:11:23: error: invalid operands to binary expression ('float' and 'double')
printf("n^3 = %f\n",(n^3.0));
                     ~^~~~
exercice14.c:12:25: error: invalid operands to binary expression ('double' and 'float')
printf("2^n = %f\n",(2.0^n));
                     ~~~^~
exercice14.c:13:25: error: invalid operands to binary expression ('double' and 'float')
printf("3^n = %f\n",(3.0^n));

CodePudding user response:

In C, ^ is the bitwise XOR operator, not exponentiation. To do exponentiation, use the pow() function from math.h

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

int main() {
    float n;

    printf("Enter a number:\n");
    scanf("%f",&n);
    printf("n^2 = %f\n",pow(n, 2.0));
    printf("n^3 = %f\n",pow(n, 3.0));
    printf("2^n = %f\n",pow(2.0, n));
    printf("3^n = %f\n",pow(3.0, n));
}

You will need the -lm compiler flag.

  •  Tags:  
  • c
  • Related