C++中可以通过多少个循环完成以下过程
With how many loops can the following process be done in C++?
我必须打印出一个三角形星形形状,用户在其中指定星号的初始数量 - 无论是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;
}
相关文章:
- 如何循环打印顶点结构
- 如何在C++中从两个单独的for循环中添加两个数组
- 递归函数计算序列中的平方和(并输出过程)
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 正在尝试了解输入验证循环
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- 循环后如何继续阅读
- Ardunio UNO解决了多个重叠的定时器循环
- Eigen如何在容器循环中干净地附加矩阵
- 在某些循环内使用vector.push_back时出现分段错误
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- 为什么我的for循环不能正确获取argv
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- while循环中while循环的时间复杂度是多少
- C++中的高效循环缓冲区,它将被传递给C样式数组函数参数
- 为什么在这个代码结束循环中没有得到结束
- 在C 中实现迭代自相关过程,使用for循环
- C++中可以通过多少个循环完成以下过程
- Masm DLL 过程在 for 循环中
- 调试过程中的无限循环