C++ 如果在 if 为 true 之后运行,为什么还会这样做

C++ Why does this else if run after the if is true

本文关键字:为什么 这样做 运行 之后 如果 if true C++      更新时间:2023-10-16
using namespace std;
int main(){
int userinp=-1,dig1=0,dig2=0,dig3=0,dig4=0;
while(userinp!=0) {
cin>>userinp;
if (userinp=0) userinp=0;
else if(userinp<0||userinp>9999) cout<<"Wrong input";
else if (userinp<10) { dig1++; userinp =-1;}
else if (userinp<100) {dig2++; userinp =-1;}
else if (userinp<1000) {dig3++; userinp =-1;}
else {dig4++; userinp =-1;}
}
cout<<dig1<<endl<<dig2<<endl<<dig3<<endl<<dig4;
return 0;
}

我正在尝试课本上的练习,但它卡在无限循环中,因为当我输入 0 时它会运行else if userinp<10。为什么?如果我在 if 熄灭后删除部分。

您在 if 条件部分中放置了一个赋值 (=( 而不是相等检查 (==(。

更改此行:

if (userinp=0) userinp=0;

对此

if (userinp==0) userinp=0;

你应该很好。

祝你好运