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

已知元素频率,如何生成对应重复次数的数组?C代码问题求解

修正C语言代码实现按输入频率生成数组

你的代码核心问题是嵌套循环的逻辑错误:每次外层循环处理5kg纸箱的元素时,内层循环都会从当前i的位置开始覆盖数组元素为10,导致之前设置的5被反复覆盖,最终结果完全不符合预期。

修正方案1:分两个独立循环填充数组

先填充所有5kg的元素,再从5kg元素的末尾位置开始填充10kg的元素:

#include <stdio.h>

int main() {
    int c5, c10;
    printf("Enter the number of 5 kg cartons: ");
    scanf("%d", &c5);
    printf("Enter the number of 10 kg cartons: ");
    scanf("%d", &c10);

    int total = c5 + c10;
    int cartons[total], i;

    // 填充5kg纸箱的元素
    for (i = 0; i < c5; i++) {
        cartons[i] = 5;
    }
    // 从c5的索引位置开始,填充10kg纸箱的元素
    for (i = c5; i < total; i++) {
        cartons[i] = 10;
    }

    // 打印验证结果
    for (i = 0; i < total; i++) {
        printf("%d\n", cartons[i]);
    }

    return 0;
}

修正方案2:用单个索引变量追踪填充位置

通过一个索引变量idx来记录当前数组填充的位置,依次添加5kg和10kg的元素:

#include <stdio.h>

int main() {
    int c5, c10;
    printf("Enter the number of 5 kg cartons: ");
    scanf("%d", &c5);
    printf("Enter the number of 10 kg cartons: ");
    scanf("%d", &c10);

    int total = c5 + c10;
    int cartons[total];
    int idx = 0;

    // 添加所有5kg元素
    for (int i = 0; i < c5; i++) {
        cartons[idx++] = 5;
    }
    // 添加所有10kg元素
    for (int i = 0; i < c10; i++) {
        cartons[idx++] = 10;
    }

    // 输出结果
    for (int i = 0; i < total; i++) {
        printf("%d\n", cartons[i]);
    }

    return 0;
}

当你输入c5=2、c10=2时,两个方案都会输出:

5
5
10
10

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 08:10:49