C language realizes the mathematical method of drawing a rhombus VS the general method


foreword

This article introduces two methods of drawing a rhombus in C language. Of course, the two methods have advantages and disadvantages, and which one you prefer is entirely up to you. Of course, I prefer method two.


1. Method 1

General approach based on double for loops.
The key lies in the characterization of several triangles.
insert image description here

#include <stdio.h>
int main()
{
    
    
	int n;
	scanf("%d", &n);
	for (int i = 0; i <= n / 2; ++i)
	{
    
    
		for (int j = n / 2 - i; j > 0; --j)
		{
    
    
			printf(" ");
		}
		for (int k = 0; k < 2 * i + 1; ++k)
		{
    
    
			printf("*");
		}
		printf("\n");
	}
	for (int i = 1; i <= n - n / 2 ; ++i)
	{
    
    
		for (int j = 1; j <= i; ++j)
		{
    
    
			printf(" ");
		}
		for (int k = n - 2 * i; k > 0; --k)
		{
    
    
			printf("*");
		}
		printf("\n");
	}

	return 0;
}

insert image description here

2. Method 2

Based on simple mathematics - the simplest form of linear programming.
insert image description here
We only need to choose the appropriate coordinate origin (very important, can simplify the calculation), and then calculate the expression corresponding to each side of the rhombus.

x + y <= n / 2
-x + y <= n / 2
-x - y <= n / 2
x - y <= n / 2

put together is

|x| + |y| <= n/2
#include <stdio.h>
#include <math.h>

int main()
{
    
    
	int n = 0;
	scanf("%d", &n);
	for (int i = -n / 2; i <= n / 2;++i)
	{
    
    
		for (int j = n / 2; j >= -n / 2; --j)
		{
    
    
			if (fabs((double)i) + fabs((double)j) <= n / 2)
				printf("*");
			else
				printf(" ");
		}
		printf("\n");
	}
	return 0;
}

insert image description here

Notice

For the second method, if you want to draw a hollow diamond, you only need to change the judgment condition to fabs((double)i) + fabs((double)j) == n / 2, isn’t it very convenient. But for method one, you have to use your brains again. As for how to write it specifically, I won't write too much here.

Summarize

That's all there is to it. Of course, both approaches have their advantages and disadvantages. No matter which method you like, don't be stingy with your praise!

Guess you like

Origin blog.csdn.net/weixin_51480590/article/details/120144621