You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用C++实现内部包含星形三角形的星形圆形图案

实现星形三角形嵌套进星形圆形的代码

以下是整合后的代码,包含详细注释,实现了将你的星形三角形嵌套进星形圆形的效果:

#include <iostream>
#include <cmath> // 用于计算点到中心的距离

using namespace std;

int main() {
    // 定义画布尺寸,确保能容纳圆形和内部的10行三角形
    const int canvas_size = 22;
    int center = canvas_size / 2; // 画布的中心坐标
    // 圆形的内外半径,形成环形星形轮廓(控制圆形的粗细)
    int circle_inner_radius = 8;
    int circle_outer_radius = 10;
    // 三角形参数:与你提供的代码一致,高度为10行
    const int triangle_height = 10;
    // 设置三角形的起始行,让它居中在圆形内部
    int triangle_start_y = center - triangle_height / 2;

    // 遍历画布的每一行(y轴方向)
    for (int y = 0; y < canvas_size; y++) {
        // 遍历画布的每一列(x轴方向)
        for (int x = 0; x < canvas_size; x++) {
            // 计算当前点到画布中心的直线距离
            double distance_to_center = sqrt(pow(x - center, 2) + pow(y - center, 2));
            // 判断当前点是否在圆形的环形区域内(生成圆形的星形轮廓)
            bool is_in_circle = (distance_to_center >= circle_inner_radius) && (distance_to_center <= circle_outer_radius);

            // 判断当前点是否在三角形区域内
            bool is_in_triangle = false;
            // 计算当前行对应的三角形行号(从0开始)
            int triangle_row = y - triangle_start_y;
            // 检查当前行是否在三角形的行数范围内
            if (triangle_row >= 0 && triangle_row < triangle_height) {
                // 计算当前三角形行的星号起始和结束列(实现居中效果,和原三角形代码逻辑一致)
                int star_start_col = center - (triangle_height - 1 - triangle_row);
                int star_end_col = center + (triangle_height - 1 - triangle_row);
                // 如果当前列在星号范围内,则属于三角形区域
                if (x >= star_start_col && x <= star_end_col) {
                    is_in_triangle = true;
                }
            }

            // 只要在圆形区域或三角形区域,就输出星号,否则输出空格
            if (is_in_circle || is_in_triangle) {
                cout << "* ";
            } else {
                cout << "  ";
            }
        }
        // 每行结束后换行
        cout << endl;
    }

    return 0;
}

代码说明

  • 圆形生成:通过计算每个点到中心的距离,筛选出环形范围内的点输出星号,形成星形圆形的轮廓。
  • 三角形嵌套:沿用你原代码的居中等腰三角形逻辑,通过坐标计算确定三角形的位置和范围,确保它位于圆形内部。
  • 叠加显示:只要点属于圆形区域或三角形区域,就输出星号,两者叠加形成嵌套效果。

内容的提问来源于stack exchange,提问作者Olyk Dominique

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 09:37:48