C++中可以通过多少个循环完成以下过程

With how many loops can the following process be done in C++?

本文关键字:过程 循环 可以通过 多少 C++      更新时间:2023-10-16

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

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

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

我用三个循环编写了代码 - 两个嵌套在一个循环中 - 使用C++其他人声称只能使用两个循环来完成,但我似乎无法弄清楚。在我的脑海中,这就像要求从 2 条线中画出一个三角形;它根本行不通。如果有人可以确认是否可以仅通过两个循环完成,如果可以,请提供提示或解释,我将不胜感激。

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

这并不意味着它总是很容易,但就您而言,幸运的是!

这个程序怎么样,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;
}

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

"

if"语句可用于确定是打印"*"还是空格。

另一种替代方法是使用创建重复字符字符串的函数。

编辑 1:
这可能派上用场,文本的居中公式:

starting_position = center_position - (character_count / 2);

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

严格来说,这段代码使用 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;
}