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

时间:2016-12-16 06:11:11

标签: c++ if-statement nested-loops

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

如果我使用else if语句它打印一个5.但是。如果我将if更改为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;
}

我一直在想是否相同。

2 个答案:

答案 0 :(得分:0)

if else-if语句中,您设置了多个条件来评估结果。

以下是这些陈述在您的案例中的作用:

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

我希望它有所帮助。

更新:(来自OP的评论)

if(row==1||row==n||row==2*n-1)
cout<<"*"; // if the above is true then show *
else
cout<<" "; // else show whitespace

if (col==1&&row<n||col==n&&row>n)
cout<<"*"; // if the above is true show *
else
cout<<" "; // else show whitespace

在此代码中,第一个和第二个语句独立工作,并且它们之间没有任何关联。如果第一个是真或假,则对第二个无关紧要,反之亦然。

此外,如果您不需要,可以省略else语句。

if (col==1&&row<n||col==n&&row>n)
cout<<"*"; // if the above is true show *
// here else will not show whitespace because it is omitted

答案 1 :(得分:0)

else if 块仅在前一个“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