我在 C++ 中遇到以下问题: 基本上这段代码:
#include<iostream>
using namespace std;
int main() {
int n=5;
for(int rows = 1; rows <= n; rows++){
for(int col = rows; col <= n; col++){
cout << "*";
}
cout << endl;
}
return 0;
}
显示此输出:
*****
****
***
**
*
当我添加到用户输入的代码时,它不起作用,这是带有输入的代码:
#include<iostream>
using namespace std;
int main() {
while(n>0){
int n;
cin >> n;
for(int rows = 1; rows <= n; rows++){
for(int col = rows; col <= n; col++){
cout << "*";
n--;
}
cout << endl;
}
}
return 0;
}
我做错了什么?我希望输入 n = 6 得到这样的结果:
***
**
*
5人份:
***
**
15 人份:
*****
****
***
**
*
正如您所看到的,模式是基于星星的数量而不是行数。
这就是问题所在,我的任务不是我需要多少行,而是打印星星直到它们消失
问题是您认为您的任务不是要打印多少行,但事实确实如此。当您不知道要打印多少行时,您还如何打印一些行数?
您应该首先确定要打印的内容,而不是一次完成所有操作并从循环开始打印星星。这种图案的星星总数是
#stars( #rows ) = ( #rows - 1) * #rows
例如,在 3 行中,您有 3*2 = 6 颗星。这是一个二次方程,对于给定的
#stars
,您可以求解 #rows
。或者,我们知道添加 n-th
行会增加 n
更多星星。
首先确定需要打印的行数:
int num_stars_to_print;
std::cin >> num_stars_to_print;
int rows_to_print = 1;
int total_stars = 1;
while ( total_stars < num_stars_to_print ) {
rows_to_print += 1;
total_stars += rows_to_print;
}
在此循环之后,您知道需要打印多少行:
rows_to_print
。第一行的星星数量是rows_to_print
。我将留给您实际打印星星。