0

This is my code. I get 3^2=1. I have included the math library.

case '^':
    printf("The result is %d\n",(num1^num2));
    break; 
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • `^` does not do what you think it does, in C++. It's a bitwise exclusive-or operator. There is no power operator in C or C++, for integers. You just have to do it the old fashioned way: multiplication. P.S. `std::pow()` does not do what you think it might do either, when integers are involved. – Sam Varshavchik Jun 13 '22 at 00:09
  • In my case I wouldn't know what the user will enter I know num1*num2 would not work in my situation. hmm would you happen to have any direction on what I should do? – Aysha Abdalla Jun 13 '22 at 00:14
  • Like I said: the old-fashioned way. That is: if you want to raise 3 to the 5th power, multiply 3 by itself five times. – Sam Varshavchik Jun 13 '22 at 00:15
  • You do NOT want to do it by multiplying. Use the pow() function. That's in the math.h library in C, or the math library in C++ – Gabe Sechan Jun 13 '22 at 00:17
  • 1
    You do NOT want to do it by `pow()` function in the math.h library. Use multiplication for `int`. – Eljay Jun 13 '22 at 00:18
  • @Eljay: `pow` is fine, since `double` can represent every `int` exactly. If you care about performance, it’s “use multiplication in exponentiation by squaring”. – Ry- Jun 13 '22 at 00:28
  • `pow()` is not fine, because `pow()` uses double and internally a log table, which can have some variation causing the double to int conversion to be off from what it would be compared to using a for loop and `int` multiplication. – Eljay Jun 13 '22 at 00:30
  • I'm new to C can someone give me an example on how I may be able to accomplish this? I am using my lecture notes and will attend office hours but in the mean time I'm confused lol. – Aysha Abdalla Jun 13 '22 at 00:30
  • 2
    @AyshaAbdalla: The duplicate links in the banner at the top of your question have answers that include code. – Ry- Jun 13 '22 at 00:31
  • @Eljay And if the exponential is a large number? If it's 2 or 3, sure use multiplication. If its a variable, you use pow not a multiplication loop. If you use multiplication for a non fixed exponential you're going to get a nice talking to from your seniors. If you're actually using big enough numbers for the double to be an issue, you should be using a more sophisticated math library and a BigInt type class. – Gabe Sechan Jun 13 '22 at 00:36
  • @GabeSechan • that does not appear to be the case in the OP's code. – Eljay Jun 13 '22 at 00:38
  • @Eljay Looking at his question where he raises num1^num2 it certainly is. And given he's writing a calculator, which commonly has a "^" button and is obviously not experienced enough to understand the perf issues of multiplication, telling him to do it that way is negligence. In fact look at his code- he's very obviously implementing a generic ^ button which would NOT be just a 2 or 3 – Gabe Sechan Jun 13 '22 at 00:40

0 Answers0