C语言销售统计二维数组程序输出异常,求修复方案
问题修复方案
你的代码出现随机异常值的核心问题是数组未初始化和数组越界访问,以下是具体修复步骤:
1. 初始化销售数据数组
C语言局部数组默认不会自动初始化,会残留内存中的随机垃圾值。你仅对单个位置执行+= value操作,其余位置仍为随机值,直接输出就会出现乱码。
将:
int sales[5][4];
修改为:
// 用{0}初始化所有元素为0 int sales[5][4] = {0};
2. 修复数组越界问题
你的sales数组定义为[5][4](对应5个产品、4个销售员),但输出循环中错误地遍历了5列,导致访问超出数组范围的内存,同时totalPerson数组只有4个元素,访问totalPerson[4]也属于越界操作。
修改输出循环的列数限制:
for (int column = 0; column < 4; column++) { printf("%7d", sales[row][column]); totalProduct[row] += sales[row][column]; totalPerson[column] += sales[row][column]; }
同时修改最后一行的总销售额输出,避免依赖越界元素,新增变量计算总销售额:
int grandTotal = 0; // ... 在产品循环内累加 grandTotal += totalProduct[row]; // ... 最后输出 printf("%7s%7d%7d%7d%7d%7d\n", "TOTAL", totalPerson[0],totalPerson[1],totalPerson[2],totalPerson[3], grandTotal);
3. 额外优化:输入合法性校验补充
原代码未限制销售员编号的上限,添加salesPersons <=4的判断,避免写入数组越界:
if(salesPersons >= 1 && salesPersons <=4 && products >= 1 && products < 6 && value >= 0)
修复后的完整代码
#include <stdio.h> int main(){ int sales[5][4] = {0}; int salesPersons, products=0; int value=0; printf("Enter salesperson number: "); scanf("%d", &salesPersons); while(salesPersons != 0){ printf("Enter product number: "); scanf("%d", &products); printf("Enter value: "); scanf("%d", &value); if(salesPersons >= 1 && salesPersons <=4 && products >= 1 && products < 6 && value >= 0) sales[products - 1][salesPersons - 1] += value; else printf("Invalid input!\n"); printf("Enter salesperson number (Enter 0 to exit inputting): "); scanf("%d", &salesPersons); } printf("%7s%7s%7s%7s%7s%7s%7s\n", "N", "P1", "P2", "P3", "P4", "P5", "TOTAL"); int totalProduct[5] = {0}, totalPerson[4] = {0}; int grandTotal = 0; for (int row = 0; row < 5; row++) { printf("%7d", row + 1); for (int column = 0; column < 4; column++) { printf("%7d", sales[row][column]); totalProduct[row] += sales[row][column]; totalPerson[column] += sales[row][column]; } grandTotal += totalProduct[row]; printf("%7d\n", totalProduct[row]); } printf("%7s%7d%7d%7d%7d%7d\n", "TOTAL", totalPerson[0],totalPerson[1],totalPerson[2],totalPerson[3], grandTotal); return 0; }
测试验证
输入你提供的测试数据后,输出会恢复正常:
Enter salesperson number: 1 Enter product number: 2 Enter value: 3 Enter salesperson number (Enter 0 to exit inputting): 0 N P1 P2 P3 P4 P5 TOTAL 1 0 0 0 0 0 2 3 0 0 0 3 3 0 0 0 0 0 4 0 0 0 0 0 5 0 0 0 0 0 TOTAL 3 0 0 0 3
内容的提问来源于stack exchange,提问作者MJee
相关产品推荐
相关产品推荐

