如何使用 C 語言程式列印弗洛伊德三角(整數)?


弗洛伊德三角是一個直角三角形,由從左上角開始的連續數字組成,最小為 1 −

例如,

1
2 3
4 5 6
7 8 9 10

示例 1

 直播演示

#include <stdio.h>
int main(){
   int rows, i,j, start = 1;
   printf("Enter no of rows of Floyd's triangle :");
   scanf("%d", &rows);
   for (i = 1; i <= rows; i++){
      for (j = 1; j <= i; j++){
         printf("%d ", start);
         start++;
      }
      printf("
");    }    return 0; }

輸出

Enter no of rows of Floyd's triangle :6
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21

示例 2

以下程式展示瞭如何反轉弗洛伊德三角 −

 直播演示

#include<stdio.h>
int main() {
   int num, i, j;
   printf("Enter number of rows: ");
   scanf("%d",&num);
   int k = num*(num+1)/2;
   for(i=num; i>=0; i--) {
      for(j=1; j<=i; j++)
      printf("%4d",k--);
      printf("
");    }    return 0; }

輸出

Enter number of rows: 7
28 27 26 25 24 23 22
21 20 19 18 17 16
15 14 13 12 11
10 9 8 7
6 5 4
3 2
1

更新於: 05-Mar-2021

168 次瀏覽

開啟你的 職業生涯

完成課程並獲得認證

開始
廣告