我設法撰寫了一些代碼,以正確的三角形形式提供所需的輸出。我對我必須修改以將其更改為等邊三角形的內容有點迷失
這是代碼:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i, j, rows;
printf("This is a program that generates a equilateral triangle of n height. \n");
printf("Enter the height of the equilateral triangle: \n");
scanf ("%d",&rows);
while (rows <= 1 )
{
printf("Invalid output, it takes two or more rows to produce a triangle.\n");
printf("Enter the number of rows for the increasing triangle: \n");
scanf("%d", &rows);
}
printf("The triangle is as follows: \n");
for (i = 1; i <= rows; i )
{
for (j =1; j <= rows; j ) {
printf(" ");
}
for (j = 1; j <= i;j ) {
printf("%d", i);
}
printf("\n");
}
return 0;
}
uj5u.com熱心網友回復:
必須修改 for 回圈的邏輯才能獲得等邊三角形。下面的代碼有效,我使用的最外層 for 回圈是每次完成內回圈后在新行中列印數字,外回圈列印新行。第一個內回圈是列印等邊三角形的空間,第二個內回圈是列印數字。
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x,y, rows;
printf("This is a program that generates a equilateral triangle of n height. \n");
printf("Enter the height of the equilateral triangle: \n");
scanf ("%d",&rows);
while (rows <= 1 )
{
printf("Invalid output, it takes two or more rows to produce a triangle.\n");
printf("Enter the number of rows for the increasing triangle: \n");
scanf("%d", &rows);
}
printf("The triangle is as follows: \n");
for(x=1; x<=rows; x)
{
for(y=x; y<=rows; y)
{
printf(" ");
}
for(y =1; y<=((2*x)-1); y)
{
printf("%d",x);
}
// Print new line
printf("\n");
}
return 0;
}

uj5u.com熱心網友回復:
一個很小的改動就會讓你的代碼變得完美 '
1.使你的第二個 for 回圈如同 for(j=rows-i;j>0;j--) 2.
在元素 printf("%d ",i );
或參考此代碼:` #include <stdio.h> #include <stdlib.h>
int main()
{
int i, j, rows;
printf("This is a program that generates a equilateral triangle of n height.
\n");
printf("Enter the height of the equilateral triangle: \n");
scanf ("%d",&rows);
while (rows <= 1 )
{
printf("Invalid output, it takes two or more rows to produce a
triangle.\n");
printf("Enter the number of rows for the increasing triangle: \n");
scanf("%d", &rows);
}
printf("The triangle is as follows: \n");
for (i = 1; i <= rows; i )
{
for (j =rows-i;j>0; j--)
{
printf(" ");
}
for (j = 1; j <= i;j )
{
printf("%d ",i);
}
printf("\n");
}
return 0;
}`
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/386856.html
標籤:C
