C程序未初始化变量编译错误:应声明新变量还是修改代码?
拔河比赛投注决策程序问题解决
题目要求
编写C程序辅助拔河比赛投注决策,需完成以下步骤:
- 先读取每队队员人数;
- 交替读取两队队员的体重(整数,单位:千克);
- 计算两队总重量,输出优势队伍(格式:
Team X has an advantage); - 分别输出两队总重量(格式:
Total weight for team 1: 重量、Total weight for team 2: 重量)。
注:两队总重量必然不等。
原代码
#include<stdio.h> int main(){ int nop, i, sum1, sum2; int team1_Weight, team2_Weight, player1, player2, answer; scanf("%d", &nop); for (i=0;i<nop;++i){ scanf("%d", &player1); team1_Weight=team1_Weight+player1; scanf("%d", &player2); team2_Weight=team2_Weight+player2; } sum1=team1_Weight; sum2=team2_Weight; answer=(sum1 > sum2); if (answer){ printf("Team 1 has an advantage\n"); printf("Total weight for team 1: %d\n", sum1); printf("Total weight for team 2: %d", sum2); }else{ printf("Team 2 has an advantage\n"); printf("Total weight for team 1: %d\n", sum1); printf("Total weight for team 2: %d", sum2); } }
问题描述
代码在在线编译器中运行正常,但提交后出现编译错误:
7066839625989131.c: In function ‘main’: 7066839625989131.c:22:9: error: ‘team2_Weight’ may be used uninitialized in this function [-Werror=maybe-uninitialized] printf("Total weight for team 2: %d", sum2); ^ 7066839625989131.c:21:9: error: ‘team1_Weight’ may be used uninitialized in this function [-Werror=maybe-uninitialized] printf("Total weight for team 1: %d\n", sum1); ^ cc1: some warnings being treated as errors
解决方案
不需要声明新变量,直接修改现有代码即可解决问题。
问题根源
编译错误的核心原因是team1_Weight和team2_Weight变量声明时未初始化,直接进行累加操作会触发未定义行为。部分在线编译器可能默认给未初始化变量赋0值,但严格的编译环境会将这类警告升级为错误。
修改后的代码
#include<stdio.h> int main(){ int nop, i; int team1_Weight = 0, team2_Weight = 0, player1, player2; scanf("%d", &nop); for (i=0;i<nop;++i){ scanf("%d", &player1); team1_Weight += player1; scanf("%d", &player2); team2_Weight += player2; } if (team1_Weight > team2_Weight){ printf("Team 1 has an advantage\n"); }else{ printf("Team 2 has an advantage\n"); } printf("Total weight for team 1: %d\n", team1_Weight); printf("Total weight for team 2: %d", team2_Weight); return 0; }
修改说明
- 初始化
team1_Weight和team2_Weight为0,确保累加操作从正确的初始值开始; - 移除冗余变量
sum1、sum2和answer,直接用team1_Weight和team2_Weight完成比较与输出,简化代码结构; - 统一总重量输出逻辑,避免重复代码;
- 添加
return 0;,符合C标准的main函数规范。
内容的提问来源于stack exchange,提问作者Lourdh Irudhaya Selvam
相关产品推荐
相关产品推荐

