Reputation: 347
I have written some code to print the value of an integer raised to an integer power. Why does this code pause for input even after I have entered 2 integers?
#include<iostream>
int main(){
int a, b;
std::cin>>a>>b;
std::cout<<std::endl<<a<<std::endl<<b<<std::endl;
int c, d;
c = a;
d = 0;
while(b){
if(b&1)
d += c;
if(b>>1){
b = b>>1;
c *= c;
}
}
std::cout<<d;
return 0;
}
I suspected that the compiler misinterprets the bitwise operator as an overloaded operator, but even if I change the condition in the while loop to
if(b/2 > 0){
b = b/2;
c *= c;
}
it still doesn't work. I have no idea what is going on here. I've tried this code in the terminal, and some online IDEs, but the result is the same.
Upvotes: 1
Views: 604
Reputation: 62636
As noted, you never assign a 0 value to b, so the loop never ends. You can replace the if test with something that does the assignment.
if(b >>= 1)
c *= c;
I prefer this to b = b >> 1
as it is more obvious you mean to assign, and don't mean to compare b == b >> 1
Upvotes: 1
Reputation: 234665
std::cin>>a>>b;
is grouped as (std::cin>>a)>>b;
so be assured that two integers are read.
Your problem is that the program loops if b
is anything other than 0.
Upvotes: 1