Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

โปรแกรม C++ พิมพ์รูปทรง 2 มิติ


ในบทช่วยสอนนี้ เราจะพูดถึงโปรแกรมที่พิมพ์รูปทรง 2 มิติ

สำหรับสิ่งนี้ เราจะได้รับพารามิเตอร์ต่างๆ ที่จำเป็นสำหรับการสร้างรูปร่าง เช่น รัศมี ความยาวด้าน และความกว้างด้าน งานของเราคือพิมพ์รูปร่างที่เหมาะสมโดยไม่มีความหนา

ตัวอย่างโค้ด C++

#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;
}

ผลลัพธ์

    *****
   **   **
  **     **
 *       *
*         *
 *       *
  **     **
   **   **
    *****