在本教程中,我们将讨论打印2D形状的程序。
为此,我们将提供制作形状所需的各种参数,例如半径,边长和边宽等。我们的任务是相应地打印没有厚度的形状。
#include <bits/stdc++.h> using namespace std; void print_circle(int radius){ for (int i = 0; i <= 2 * radius; i++){ for (int j = 0; j <= 2 * radius; j++){ double distance = sqrt((double)(i - radius) * (i - radius) + (j - radius) * (j - radius)); if (distance > radius - 0.5 && distance < radius + 0.5) printf("*"); else printf(" "); } printf("\n"); } } void print_rectangle(int l, int b){ int i, j; for (i = 1; i <= l; i++){ for (j = 1; j <= b; j++) if (i == 1 || i == l || j == 1 || j == b) printf("*"); else printf(" "); printf("\n"); } } void print_triangle(int side){ int i, j; for (i = 1; i <= side; i++){ for (j = i; j < side; j++) printf(" "); for (j = 1; j <= (2 * i - 1); j++){ if (i == side || j == 1 || j == (2 * i - 1)) printf("*"); else printf(" "); } printf("\n"); } } void print_hexagon(int length){ int l, j, i, k; for (i = 1, k = length, l = 2 * length - 1; i < length; i++, k--, l++){ for (j = 0; j < 3 * length; j++) if (j >= k && j <= l) printf("*"); else printf(" "); printf("\n"); } for (i = 0, k = 1, l = 3 * length - 2; i < length; i++, k++, l--){ for (j = 0; j < 3 * length; j++) if (j >= k && j <= l) printf("*"); else printf(" "); printf("\n"); } } void calc_pattern(int choice){ int radius, length, breadth, side; switch (choice){ case 1: radius = 4; print_circle(radius); break; case 2: length = 3, breadth = 8; print_rectangle(length, breadth); break; case 3: side = 6; print_triangle(side); break; case 4: side = 4; print_hexagon(side); break; default: printf("Invalid choice\n"); } } int main(){ int choice = 1; calc_pattern(choice); return 0; }
输出结果
***** ** ** ** ** * * * * * * ** ** ** ** *****