[英]How to print an Isosceles triangle in C++
I'm trying to create an isosceles triangle with '*' symbol from user's input in C++.我正在尝试根据 C++ 中的用户输入创建一个带有“*”符号的等腰三角形。
For example, with user's input of 5, I must get:例如,用户输入 5,我必须得到:
*
**
***
****
*****
****
***
**
*
I'm getting only:我得到的只是:
*
**
***
****
*****
My c++ code:我的 c++ 代码:
void askData(int &n){
cout<<"Enter a number: ";
cin>>n;
}
void print(int A){
for(int j=1;j<=A;j++)
cout<<"*";
cout<<endl;
}
void createIsoscTriangle(int n){
for(int i=1;i<=n;i++){
print(i);
}
int main()
{
int n;
askData(n);
createIsoscTriangle(n);
return 0;
}
How can I get the correct form of the isosceles triangle?如何获得等腰三角形的正确形式?
The pattern of stars is 1
, 2
, 3
, ...
, n
, n - 1
, n - 2
, ...
, 1. as Brian mentioned in the comments.星星的图案是1
, 2
, 3
, ...
, n
, n - 1
, n - 2
, ...
, 1. 正如 Brian 在评论中提到的那样。 So, Numbers of stars for each line would be n - abs(n - i)
, where abs is the absolute value of n - i
, and that should work for any n
not just 5
.因此,每行的星数将为n - abs(n - i)
,其中 abs 是n - i
的绝对值,这应该适用于任何n
而不仅仅是5
。
I've modified your createIsoscTriangle function to be the following:我已将您的 createIsoscTriangle function 修改为以下内容:
void createIsoscTriangle(int n) {
for(int i = 1; i <= n * 2 - 1; i++)
print(n - abs(n - i));
}
Let's try it for n = 5
.让我们试试n = 5
。 It would print the figure you mentioned.它会打印你提到的数字。
*
**
***
****
*****
****
***
**
*
You only print sequence 1 2 3 4 5
.您只打印序列1 2 3 4 5
。 You also need a loop which would count down.您还需要一个可以倒计时的循环。
void createIsoscTriangle(int n) {
for(int i = 1; i <= n; i++)
print(i);
for(int i = n-1; i >= 1; i--)
print(i);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.