Output diamond pattern C language and Python implementation

Topic:

  • Requirement, input the width n of the rhombus , which represents the number of * in the widest place, for example, n = 7 in the figure below
    Insert picture description here

C language implementation

  • skill:
  • (1) Divide the rhombus (as shown in the figure above) into upper triangles, and realize inverted triangles.
  • (2) were found on each line of output space law with an asterisk *
#include<stdio.h>
int main()
{
    
    
	int n, m, c, i;
	printf("请输入*号的个数,代表菱形宽度:\n");
	scanf("%d", &n);
	//打印上三角形
	for(i=1; i<= (n + 1)/2; i++)
	{
    
    
		// 打印空格
		for(m=1; m<= (n + 1)/2 - i; m++)
		{
    
    
			printf(" ");
		}
		// 打印 *, 这里 *的个数 和行数是有关系的, 第i行就有  2*(i-1)+1 个 *
		for(c=1; c<=2*(i-1)+1; c++)
		{
    
    
			printf("*");
		}
		printf("\n");
	}

	// 下面再来一个循环,打印倒三角, 上三角和倒三角拼成一个 菱形
	for(i=1; i<(n/2 + 1); i++)
	{
    
    
		// 打印空格
		for(c=1; c<=i; c++)
		{
    
    
			printf(" ");
		}
		// 打印*号, 这里加入打印7个宽的菱形,这里倒三角是(表示*数) 5,3,1  ,所以 (n+1)/2 - i) 表示倒着的行号 3, 2, 1, 在利用 (行号*2 -1)的行数计算。
		for(m=1; m<=((n+1)/2 - i) * 2 -1; m++)
		{
    
    
			printf("*");
		}
		printf("\n");
	}
	return 0;
}

python implementation

  • The writing is a bit messy, but it's just such a thing, referring to the implementation of C language, the logic inside has not changed, just copied it. It's just that the language is different, and the code is different when it is implemented.
n = int(input("请输入菱形的宽度:"))
# 打印上三角
for i in range(1, int((n + 1)/2) + 1):
    print(" "*int(((n + 1)/2 - i)) , "*"*(2*(i-1)+1))

for i in range(1, int((n + 1)/2)):
    print(" "*i , "*"*((int((n+1)/2) - i) * 2 - 1))

# 1. 利用python字符串可以用 乘法运算符,省去两个for循环
# 2. 得到的结果是 浮点类型~,需要转换为int类型
print(type(5/3))
# 3. 另外需要注意的是,连个字符串用 , 连接,不能使用 + , 加号会使 第一个 空格没有

Guess you like

Origin blog.csdn.net/pythonstrat/article/details/112743240