本題要求實現函數輸出n行數字金字塔。
C程序
#include <stdio.h>
#include <stdlib.h>
/*
// 浙大版C語言PAT 求m到n的和
int sum(int m , int n);
int main()
{
int m,n;
scanf("%d %d",&m,&n);
printf("sum = %d\n",sum(m,n));
return 0 ;
}
int sum(m ,n)
{
int sum=0,i;
for(i = m; i<=n; i++ )
{
sum += i;
}
return sum;
}
*/
/*取最大值
int max(int a,int b);
int main()
{
int a,b;
scanf("%d %d",&a,&b);
printf("max = %d\n",max(a,b));
return 0 ;
}
int max(int a,int b)
{
if(a>=b)
return a;
else
return b;
}
*/
// 實現輸出n行數字金字塔
void pyramid(int n);
int main()
{
int n;
scanf("%d",&n);
pyramid(n);
// printf("i am C");
return 0 ;
}
void pyramid(int n)
{
int i,j,k;
for(i = 1;i<=n;i++)
{
for(j = 1;j<=n-i;j++)
{
printf(" ");
}
for(k = 1;k<=i;k++)
{
printf("%d ",i);
}
printf("\n");
}
}
C++:
#include <iostream>
#include <iomanip>
using namespace std;
void pyramid(int n);
int main()
{
int n;
cin>>n;
pyramid(n);
//cout<<"i am C++";
return 0 ;
}
void pyramid(int n)
{
int i,j,k;
for(i = 1;i<=n;i++)
{
for(j = 1;j<=n-i;j++)
{
cout <<" ";
}
for(k = 1;k<=i;k++)
{
cout <<i <<" ";
}
cout <<endl;
}
}
Python:
# n = 5 # 這裡是輸出總行數
n = int(input("please input a num: "))
for i in range(1,n+1):
for j in range(1,n-i+1):
print(" ",end="")
# print(" ")
for k in range(1,i+1):
print(i,end = " " )
print("\n")