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

如何在C++中排序数组并输出对应三角形的编号?

解决三角形面积排序后对应原编号输出的问题

现有代码仅对面积数组进行排序,丢失了与原三角形编号的关联,导致无法输出排序后对应的原始编号。以下是修改方案,通过绑定编号与面积的关系实现需求:

修改思路

  • 新增编号数组indices,存储每个三角形的原始编号(1~n)
  • 排序时同步交换面积数组和编号数组的元素,保持两者的对应关系
  • 输出时使用编号数组的元素作为原三角形编号,并格式化面积为两位小数

修改后的完整代码

#include <iostream>
#include <math.h> 
#include <iomanip> // 用于格式化小数输出
using namespace std;

int main()
{
    int i, j, a, b, c, n;
    double s, ar, area[10];
    int indices[10]; // 存储每个三角形的原始编号
    cout << "Enter a number between 1 and 10: " << endl;
    cin >> n;
    for (i = 0; i < n; i++)
    {
        cout << "Enter the sides of triangle " << (i + 1);
        cout << ":" << endl;
        cin >> a >> b >> c; // 简化输入写法
        s = (a + b + c) / 2.0; // 用2.0避免整数除法导致的精度丢失
        ar = sqrt(s * (s - a) * (s - b) * (s - c)); // 用sqrt计算平方根更高效
        area[i] = ar;
        indices[i] = i + 1; // 记录当前三角形的原始编号
    }
    // 冒泡排序,同步交换面积和对应编号
    for (i = 0; i < n; i++)
    {
        for (j = i + 1; j < n; j++)
        {
            if (area[i] > area[j])
            {
                // 交换面积值
                double tempArea = area[i];
                area[i] = area[j];
                area[j] = tempArea;
                // 同步交换对应编号,保持关联
                int tempIndex = indices[i];
                indices[i] = indices[j];
                indices[j] = tempIndex;
            }
        }
    }
    // 设置输出格式,保留两位小数
    cout << fixed << setprecision(2);
    for (i = 0; i < n; i++)
    {
        cout << "Area of triangle " << indices[i] << ": " << area[i] << endl;
    }
    return 0;
}

关键修改说明

  1. 编号数组绑定:新增indices数组,在输入阶段就记录每个三角形的原始编号(从1开始),确保排序后能追溯原编号
  2. 同步排序:冒泡排序时,交换面积元素的同时交换对应位置的编号元素,保证面积和编号始终一一对应
  3. 精度优化:计算半周长s时使用2.0避免整数除法,用sqrt()替代pow(..., 0.5)更高效地计算平方根
  4. 格式输出:添加iomanip头文件,通过fixed << setprecision(2)让面积输出保留两位小数,与示例格式一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 23:35:22