How to increase strength

I am very new to C

I'm trying to give something to something.

eg. 5 ^ 3 = 125;

but when i code

#include <math.h> ... printf("%d", 5^3); 

I get 6. Am I doing something fundamentally wrong?

+6
source share
5 answers

^ is the bitwise XOR operator in C.

5 is 101 in binary representation, and 3 is 011 . So, 101 XOR 011 = 110 , which is 6 in decimal form.

You want pow(5,3) (which is available after turning on math.h , just like you). Please note, however, that it acts on non-integer pairs, so your return value will be a floating point and not at all exact. If you need an exact integer exponentiation, you need to either use an additional library or implement your own power function. This is not so difficult, for the algorithm, see squaring . Standard C does not include a function for integer exponentiation. In any case, with an integer degree of exponentiality, it is important to take care of the overflow, which can happen for small input values.

In addition, to print the returned double, you need to either convert double to int printf("%d", (int)pow(5,3)) , or print it as a floating point printf("%f", pow(5,3))

+15
source

^ is an XOR operator in C.

Instead, you should use the pow function from math.h , however pow returns double

 #include <math.h> ... printf("%d", (int)pow(5, 3)); 
+3
source

You should use pow(5,3) .

You are using the bitwise operator XOR ( ^ ): in binary format 101 ^ 011 , which is 110 or 6 (your current answer) in denaret.

+2
source

In C, there is a no operator for exponentiality (cardinality). ^ used by the bitwise XOR operator in C. Executing 5^3 will return 6 , not 125 . For exponentiation, you can use the standard pow library function.
Signature:

 double pow(double x, double y); 

Title:

 #include <math.h> 

Change

 printf("%d", 5^3); 

to

 printf("%d",(int)pow(5,3)); 

In C ++, do not use <math.h> . You can use <cmath> instead.

+1
source

Others have already recommended using the pow function from math.h because ^ not the right operator to execute power. Alternatively, you can also write your own nutrition function just for fun.

 int power(int base, int exp) { int result = 1; while(exp) { result = result * base; exp--; } return result; 

Inside main:

 printf("%d\n", power(5,3)); 

In this case, you do not need to use the translation operator, since pow() does not work with int.

0
source

All Articles