gpt4 book ai didi

c - 打印语句不断打印多次而不是一次?

转载 作者:行者123 更新时间:2023-11-30 15:10:57 26 4
gpt4 key购买 nike

这是我当前的代码:

#include <stdio.h>
#include <string.h>

int main(void)
{
char names[2048][32];
int removed[2048];

int game;
int n;

int m;
int k;
int l;

int i;
int j;
int round;
int pos;

int lowest;
int next;

// Read the number of games to be played
scanf("%d",&n);

// Process each game
for(game = 1; game <= n; game++)
{

// Read the number of friends
scanf("%d",&m);

// Read the names of each friend
for(i=0;i<m;i++)
{
scanf("%s",names[i]);

// Mark the friend as having not been eliminated
removed[i] = 0;
}

// Read the number of rounds and the number of "Ducks"
scanf("%d %d", &k,&l);

// If the number of rounds is greater than the number of friends
// Jimmy will boot all his friends
if(k >= m)
{
printf("Jimmy has friends no more.\n\n");
continue;
}

// Simulate the game round by round
pos = 0;
for(round=0;round<k;round++)
{
// Walk around the circle stopping at the lth remaining friend
for(i=0; i<=l; pos = (pos+1)%m)
{
if(!removed[pos])
i++;

if(i == l+1)
// Give the friend we stopped at the boot
removed[pos]=1;

}
}

lowest = 0;
// Loop for each remaining friend
for(i=0;i<(m-k);i++)
{
// Find the lowest numbered remaining friend
while(removed[lowest])
lowest++;

// Find the friend with the first name alphabetically
next = lowest;
for(j=lowest;j<m;j++)
{
if(!removed[j] && strcmp(names[j],names[next]) < 0)
next = j;
}

// Print the name of the next friend and remove him/her from the circle
removed[next] = 1;
printf("Game %d:\n", game);
printf("%s\n", names[next]);
}
printf("\n");


}
return 0;
}

这是它的输入和输出:

Input:
2
3
Bob
Cody
John
2 2
Game 1: (the output)
Cody(the output)

8
Carol
Casey
Nick
Kirsten
Ben
Bo
Billy
Heather
3 4
Game 2: (The output)
Billy(The output)
Game 2:(The output)
Bo(The output)
Game 2:(The output)
Carol(The output)
Game 2:(The output)
Kirsten(The output)
Game 2:(The output)
Nick(The output)

如何让“Game 2:”printf 语句只显示一次?我尝试将它放在代码的不同部分,但我仍然没有得到它。为了更好地理解我想要得到的东西,这是我想要做的:

Output:
Game 1:
Cody
Game 2:
Billy
Bo
Carol
Kirsten
Nick

最佳答案

将“Game”的打印移至 for 循环之外:

    // print "Game" here
printf("Game %d:\n", game);
// Loop for each remaining friend
for(i=0;i<(m-k);i++)
{
// Find the lowest numbered remaining friend
while(removed[lowest])
lowest++;

// Find the friend with the first name alphabetically
next = lowest;
for(j=lowest;j<m;j++)
{
if(!removed[j] && strcmp(names[j],names[next]) < 0)
next = j;
}

// Print the name of the next friend and remove him/her from the circle
removed[next] = 1;
// print "game" was here
printf("%s\n", names[next]);
}

关于c - 打印语句不断打印多次而不是一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35923060/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com