如何使用 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP