[英]Bitwise operators in c++ and overloading
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?
为什么即使我输入了2个整数,该代码也会暂停输入?
#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 我怀疑编译器将按位运算符误解为重载运算符,但是即使我将while循环中的条件更改为
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.
我已经在终端和一些在线IDE中尝试了此代码,但是结果是相同的。
std::cin>>a>>b;
is grouped as (std::cin>>a)>>b;
分组为
(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. 您的问题是,如果
b
为0以外的任何值,程序就会循环执行。
As noted, you never assign a 0 value to b, so the loop never ends. 如前所述,您永远不会为b分配0值,因此循环永远不会结束。 You can replace the if test with something that does the assignment.
您可以将if测试替换为执行赋值的操作。
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
我更喜欢
b = b >> 1
,因为更明显的是您要分配,而不是要比较b == b >> 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.