2016-12-16 68 views
-8

爲什麼當我使用if語句時,程序會給我一個不同的結果。當我使用if語句時,爲什麼程序會給我一個不同的結果

如果我使用else if語句它會打印一個5.然而,如果我更改其他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

if'了'if'只計算當包含'if'條件是錯誤的...它改變了事情(c1){} else if(c2){}'等價於if(c1){} if(!c1 && c2){}'。 –

回答

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 
+0

你能告訴我,如果我改變其他if if語句會發生什麼? – Shawn99

+0

我更新了我的答案,你可以看看。如果它對您有幫助,請將其標記爲答案。 – Ahmar

0

否則,如果塊將執行僅在緊接之前的「如果」不執行塊。例如:

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 
在`其他
相關問題