如何使用 C 語言程式以多種格式列印數字?
問題
用 C 語言,列印不同格式(如金字塔、直角三角形)的數字的邏輯是什麼?
解決方案
為了用不同的模式列印數字或符號,我們可以在程式碼中利用 for 迴圈。
示例 1
以下 C 程式可列印金字塔 −
#include<stdio.h> int main(){ int n; printf("Enter number of lines: "); scanf("%d", &n); printf("
"); // loop for line number of lines for(int i = 1; i <= n; i++){ // loop to print leading spaces in each line for(int space = 0; space <= n - i; space++){ printf(" "); } // loop to print * for(int j = 1; j <= i * 2 - 1; j++){ printf(" * "); } printf("
"); } return 0; }
輸出
Enter number of lines: 8 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
示例 2
以下程式以直角三角形(圖案)的形式顯示數字 −
#include <stdio.h> void main(){ int i,j,rows; printf("Input number of rows : "); scanf("%d",&rows); for(i=1;i<=rows;i++){ for(j=1;j<=i;j++) printf("%d",j); printf("
"); } }
輸出
Input number of rows : 10 1 12 123 1234 12345 123456 1234567 12345678 123456789 12345678910
廣告