有多少循环可以在C ++中完成以下过程?

时间:2014-02-17 13:31:19

标签: c++

我必须打印出一个三角星形状的形状,用户可以指定星号的初始数量 - 无论是10,25还是30。

***** (5) 
 ***  (3)
  *   (1)

OR

********** (10)
 ********
  ******
   ****
    **
     *

我已经用三个循环编写了代码 - 两个嵌套在一起 - 使用C ++有人声称它只能使用两个循环来完成,但我似乎无法弄明白。在我的脑海里,就像要求从两条线中画出一个三角形;它根本无法工作。如果有人能确认是否可以只用两个循环来完成,我会很感激,如果有,请提供提示或解释。

4 个答案:

答案 0 :(得分:1)

要使用2个for循环,您将有一个循环用于行,另一个循环用于字符。

" if"声明可用于确定是否打印' *'或空间。

另一种选择是使用创建重复字符串的函数。

编辑1:
这可能会派上用场,以文字为中心:

starting_position = center_position - (character_count / 2);

答案 1 :(得分:1)

一个循环足以枚举所有行。要在第N行打印N个空格,请使用std::string(N, ' ')构造函数。

答案 2 :(得分:1)

理论计算机科学说每个问题都可以在一个循环中解决。

这并不意味着它总是很容易,但在你的情况下,幸运的是它!

这个程序怎么样,http://ideone.com/nTnTC8

#include <iostream>
using namespace std;

int main(int argc, char* argv[]) {

    int startNum = 0;
    cin >> startNum;

    if (startNum <= 0) return 1;

    cout << startNum << endl;
    int numCols = startNum;
    int numRows = (startNum + 1) / 2;

    if (numCols % 2 == 0) {
        ++numRows;
    }

    int numFields = numCols * numRows;

    for (int currentField = 0; currentField < numFields; ++currentField) {
        int currentRow = currentField / numCols;
        int currentCol = currentField % numCols;

        if (currentCol < currentRow) cout << "-";
        else if (currentCol > (numCols - currentRow - 1)) 
            if (currentRow == numRows - 1 && currentCol == numCols / 2) 
                cout << "^";
            else cout << "_";
        else cout << "*";

        if (currentCol == numCols - 1) cout << endl;
    }

    return 0;
}

答案 3 :(得分:1)

严格地说,这段代码使用2个循环来实现这个技巧:

int n, s, z;

cout << "Enter the width \n";
cin >> n;

// for each row
for (int i = 0; i < n/2+1; i++) {   

    z = i; // set number of spaces to print
    s = (n-i*2) + (i == n/2 ? (1-n%2) : 0); // set number of stars to print

    // still something to print
    while (z+s > 0) {
        if ( z ) {
            cout << " ";
            z--;
        } else if ( s ) {
            cout << "*";
            s--;
        }
    }

    cout << endl;
}