C++ 当我使用if语句时,为什么程序会给出不同的结果

C++ 当我使用if语句时,为什么程序会给出不同的结果,c++,if-statement,nested-loops,C++,If Statement,Nested Loops,当我使用if语句时,为什么程序会给出不同的结果 如果我使用else If语句,它将打印一个5。然而如果我将elseif改为If语句,它会打印出完全不同的图片。谁能告诉我为什么 #include<iostream> using namespace std; // Print 5. int main() { int n=5; for(int row=1;row<=2*n-1;row++) { for(int col=1;col<=n;col++)

当我使用if语句时,为什么程序会给出不同的结果

如果我使用else If语句,它将打印一个5。然而如果我将elseif改为If语句,它会打印出完全不同的图片。谁能告诉我为什么

#include<iostream>
using namespace std;

 // Print 5.
 int main() {
 int n=5;
 for(int row=1;row<=2*n-1;row++)    
  {
  for(int col=1;col<=n;col++)
   {
   if(row==1||row==n||row==2*n-1)
    cout<<"*";
   else if (col==1&&row<n||col==n&&row>n)
    cout<<"*";
   else
    cout<<" ";
  } 
 cout<<endl;
 }
 return 0;
}
我一直认为if和elseif是相同的。

在if-elseif语句中,您放置了多个条件来评估结果

以下是这些陈述在您的案例中的工作方式:

if(row==1||row==n||row==2*n-1)
cout<<"*"; //if true then put * or if false then move down
else if (col==1&&row<n||col==n&&row>n)
cout<<"*"; // if the first is false and the 2nd one is true then put * or if false then move down
else
cout<<" "; // if both of the above statements are not true put whitespace
仅当上一个if块未执行时,才会执行else if块。例如:

int a = 9;
if (a==9)         //true and executed
     cout<<"is 9";
else if(a<5)      //not executed since the if(a==9) block executed
     cout<<"is less than 5";
鉴于:

int a = 9;
if (a==9)         //true and executed
     cout<<"is 9";
if (a<5)           //true and executed regardless of the previous if block
     cout<<"is less than 5";

在else中,如果仅当封闭的if条件为false时才计算if。。。它改变了事物使用一种或另一种形式。。。if c1{}else if c2{}等价于ifc1{}if!c1&&c2{}。你能告诉我如果我把elseif语句改成if语句会发生什么吗?我更新了我的答案,你可以看一下。如果有帮助,请将其标记为答案。
int a = 9;
if (a==9)         //true and executed
     cout<<"is 9";
else if(a<5)      //not executed since the if(a==9) block executed
     cout<<"is less than 5";
is 9
int a = 9;
if (a==9)         //true and executed
     cout<<"is 9";
if (a<5)           //true and executed regardless of the previous if block
     cout<<"is less than 5";
is 9
is less than 5