程序输出错误的金额

时间:2018-10-28 00:45:40

标签: c sum

team1sum / team2sum应该获得每个playerWeight1 / playerWeight2的总和并打印出来。

我的team1sumteam2sum打印出错误的数字。

可以看到正确的输出here

#include <stdio.h>

int main() {

    int i, howManyPlayers, playerWeight1, playerWeight2, 
        team1sum = 0, team2sum = 0;

    scanf("%d", &howManyPlayers);

    for (i = 0; i < howManyPlayers; i++){
        scanf("%d", &playerWeight1);
        scanf("%d", &playerWeight2);
        team1sum = team1sum + playerWeight1;
        team2sum = team2sum + playerWeight2;
    }

    if (team1sum > team2sum){
        printf("Team 1 has an advantage\n");
        printf("Total weight for team 1: %d\n", &team1sum);
        printf("Total weight for team 2: %d", &team2sum);
    }

    else {
        printf("Team 2 has an advantage\n");
        printf("Total weight for team 2: %d\n", &team2sum);
        printf("Total weight for team 1: ", &team1sum);
    }

    return 0;
}

2 个答案:

答案 0 :(得分:1)

您的printf需要一个int,而不是int的地址,因此删除&运算符。

printf("Total weight for team 2: %d\n", team2sum);
printf("Total weight for team 1: %d", team1sum);

应该可以解决问题。

答案 1 :(得分:0)

我运行了您的代码,看来实际的总和是正确计算的。

通过从打印语句中删除&,您应该获得预期的输出。

请记住,当您使用printf打印时,格式确实很重要,并且将&打印到int与打印int是不同的。 / p>