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

C++打印空心菱形图案代码异常求助

奇数行空心菱形打印问题

我写了一段C++代码,用来打印奇数行的空心菱形(由星号和空格组成),代码如下:

#include <iostream>
using namespace std;
int main(){
    int tr;
    cin >> tr;
    //first row
    int firststar = 1;
    while (firststar <= tr){
        cout << "*";
        firststar++;
    }
    cout << endl;

int firsthalf = 1;
while (firsthalf <= (tr-1/2)) {
    //stars
    int star1 = 1;
    while (star1 <= (((tr-1/2)+1)/2-firsthalf) ){
        cout << "*" ;
        star1++;
    }
    //spaces
    int spaces1 = 1;
    while (spaces1 <= 2 * firsthalf - 1){
        cout <<" ";
        spaces1++;
    }

    //stars
    star1 = 1;
    while (star1 <= (((tr-1/2)+1)/2-firsthalf) ){
        cout << "*" ;
        star1++;
    }
    firsthalf++;
    cout << endl;
}

int secondhalf = 1;
while (secondhalf <= ((tr-1) /2)-1){
    //stars
    int star2 = 1;
    while (star2 <= secondhalf+1){
        cout << "*" ;
        star2++;
    }

    //spaces
    int spaces2 = 1;
    while (spaces2 <= 2 * ((tr - 1) / 2 - secondhalf) - 1){
        cout << " ";
        spaces2++;
    }

    //stars
    star2 = 1;
    while (star2 <= secondhalf+1){
        cout << "*" ;
        star2++;
    }
    cout<< endl;
    secondhalf++;
}
//last row
int laststar = 1;
while (laststar <= tr){
    cout << "*";
    laststar++;
}
return 0;
}

我反复检查了星号与空格的逻辑,运行后仍出现第一部分之后打印多余空格/行的问题,错误效果如下:

运行错误效果

问题分析与修正

核心问题出在整数运算的优先级错误和循环条件逻辑偏差:

  1. 原代码中tr-1/2会先计算1/2(整数除法结果为0),变成tr-0=tr,导致上半部分循环次数远超过实际需要
  2. 上半部分的星号数量计算也存在同样的优先级问题,导致星号和空格的数量逻辑混乱

修正后的代码:

#include <iostream>
using namespace std;

int main(){
    int tr;
    cin >> tr;

    // 打印首行
    for(int i = 0; i < tr; i++){
        cout << "*";
    }
    cout << endl;

    // 打印上半部分(除首行外的上半段)
    int mid = (tr - 1) / 2;
    for(int i = 1; i <= mid; i++){
        // 左侧星号
        for(int j = 0; j < mid - i + 1; j++){
            cout << "*";
        }
        // 中间空格
        for(int j = 0; j < 2 * i - 1; j++){
            cout << " ";
        }
        // 右侧星号
        for(int j = 0; j < mid - i + 1; j++){
            cout << "*";
        }
        cout << endl;
    }

    // 打印下半部分(除末行外的下半段)
    for(int i = 1; i < mid; i++){
        // 左侧星号
        for(int j = 0; j < i + 1; j++){
            cout << "*";
        }
        // 中间空格
        for(int j = 0; j < 2 * (mid - i) - 1; j++){
            cout << " ";
        }
        // 右侧星号
        for(int j = 0; j < i + 1; j++){
            cout << "*";
        }
        cout << endl;
    }

    // 打印末行
    for(int i = 0; i < tr; i++){
        cout << "*";
    }
    cout << endl;

    return 0;
}

关键修改点

  • 用mid = (tr - 1) / 2明确计算菱形的中间行索引,避免优先级错误
  • 把原有的while循环替换为更直观的for循环,逻辑更清晰
  • 修正上半部分的循环条件,确保循环次数正确
  • 调整下半部分的循环条件,去掉多余的行

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 14:36:01