提问人:Lourdh Irudhaya Selvam 提问时间:7/18/2023 最后编辑:ChrisLourdh Irudhaya Selvam 更新时间:7/18/2023 访问量:56
我应该声明一个新变量,还是修改我的代码?
shoud I declare a new variable, or modify my code?
问:
问题指出:
您决定押注拔河国家赛的最后一场比赛 冠军。
在比赛开始前,将显示球员的姓名和体重, 按团队交替(团队 1 玩家 1、团队 2 玩家 1、团队 1 玩家 2,依此类推)。每边都有相同数量的玩家。你 记录显示的球员体重并计算总数 每支球队的权重,以告知您的投注。你编写一个 C 程序来 协助。
您的程序应首先读取一个整数,该整数指示 每个团队的成员。然后,程序应该读取球员的权重 (代表千克的整数)按团队交替。
计算出每个团队的总权重后,程序应 显示文本“Team X has an advantage”(将 X 替换为 1 或 2 取决于哪个团队的总权重更大)。
然后,您将显示文本“团队 1 的总重量:”,后跟 团队 1 的权重,然后是“团队 2 的总权重:” 团队 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
答:
2赞
Chris
7/18/2023
#1
如评论中所述,您已经使用过它们并在初始化它们之前。这些变量的初始值是不确定的,这使得程序的输出无法确定。team_weight1
team_weight2
可能是在线判断编译器给了这些您期望的值(可能),但这不能指望。解决方案是简单地显式初始化它们。0
评论
team1_Weight=team1_Weight+player1;
team1_Weight
team1_Weight+player1
team1_Weight