2013-10-16 58 views
0

我需要打印星號以下面的方式:麻煩與計算值嵌套For循環

XXXXXXX
_xxxxx
__xxx

(7,5,3)

XXXXXX
_xxxx
__xx

(6,4,2)

有一個用於輸入最大數量星號和輸入行數的輸入。最下面的一排不得少於兩個星號。

我意識到這需要嵌套for循環。

我有以下代碼:

for (rows = 1; rows < ((toprow/2) + (toprow % 2)); rows++) 
    { 
     for() 
     cout << endl;          
    } 

我有一個很難搞清楚內for循環。

+0

不斷減去2從第一個號碼,然後使用if語句檢查,如果該值大於或等於二 – pyCthon

+0

怎麼樣的格式,雖然?滯後的空間。 – ghal

回答

3
for (rows = 1; rows < ((toprow/2) + (toprow % 2)); rows++) 
    { 
    if(rows <= maxrows) 
     { 
     // first the leading underscores 
     for (int k=1; k<rows; ++k) 
      cout << "_"; 

     // then the asterisks 
     for (int k=1; k <= toprow - 2*rows + 2; ++k) 
      cout << "*"; 
     cout << endl;          
     } 
    } 

編輯:你的外循環不會在正確的行數的迭代。它應該是這樣的:

for (int rows = 1; rows <= (toprow/2); rows++) 
    ... 
+0

嗯...我正在嘗試這個,但我沒有得到任何輸出。 – ghal

+0

工作正常,抱歉...並且謝謝你! – ghal

+0

看起來像輸入是偶數行,它不打印最後一行(**)。 – ghal

0

你可能想是這樣的:

int initial = 7; 
int copy = initial; 
int rows = 3; 
for (int i = 0; i < rows; i++) 
{ 
    std::cout << std::string(initial - copy, ' ') 
       << std::string(copy, '*') << std::endl; 
    copy -= 2; 
} 

這是假設行作爲一個有效的輸入提供。

0

使用此C代碼作爲參考。它將打印最多行數或最後一行開始小於2的時間,以較早者爲準。這段代碼的

#include<stdio.h> 
    int main() 
    { 
    //topstar have the number of stars in top row 
    int row=7; 
    int topstar=7; 
    int i,j,k,l,last; 

    for(i=0;i<row;i++) 
    { 
    //last contain the number of stars in last row 
    last=topstar - 2*i; 

    if(last<2) 
    break; 

    for(k=0;k<i;k++) 
     printf("_"); 
    for(j=0;j<last;j++) 
     printf("*"); 
    for(l=0;l<i;l++) 
     printf(" "); 
     printf("\n"); 
    } 
    return 0; 
} 

輸出是

enter image description here

0
spaces = 0; 
asterix = toprow; 
for (rows = 1; rows < ((toprow/2) + (toprow % 2)) && asterix > 1; rows++) 
    { 
     for (i = 0; i < spaces; i++) 
     print -; 

     for (i = 0; i < toprow; i++) 
     print *; 

     println 

     spaces+=2; 
     asterix -=2; 

    }