我怎样才能在一个循环内完美地形成一个循环呢?

时间:2013-09-05 14:26:24

标签: c loops

我需要制作一个如下所示的程序:

Player name 1:   <input> 
Player name 2:   <input> 
<output> <output> 
(Player 1's)Score1: <input1>
            Score2: <input2> 
(player 2's)Score1: <input1>
            Score2: <input2>

(player 1's)<output1>
            <output2> 
(player 2's)<output1>
            <output2>

或准确地说:

Number     Player Name     Score
                           Game1     Game2
------     -----------    -------   -------
 [1]         <name1>      <score1>  <score2> 
 [2]         <name2>      <score1>  <score2>

我需要创建一个循环来指示名称旁边的数字,但我无法弄清楚如何操作。

这是我的代码:

int main()

{
    int x=1;
    char player[PLAYERS][LENGTH] = {"-----"};
    char scorex[GAME][LENGTH] = {"0.00"};

    int i,j;//COUNTERS

    for (i=0; i<PLAYERS; i++)
    {
        printf("Player Name %d:\t",x);
        fgets(player[i], LENGTH, stdin);
        x++;
    }   

    for (i=0;i<PLAYERS;i++)
    {
        printf("%10s\n", player[i]);
    }

    for (x=1; x<=PLAYERS; x++)
    {
        printf("score %d:\t", x);
        for (i=0 ;i<GAME; i++)
        {
        fgets(scorex[i], LENGTH, stdin);
        }
        printf("%5s\n", scorex[i]);
    }
    return 0;
}

循环怎么办? 帮助

2 个答案:

答案 0 :(得分:0)

只是解决输出部分,以下代码是一种方法来执行您所描述的内容:(格式化需要一些工作)

#include <windows.h>
#include <ansi_c.h>

enum    {
    name1,
    name2,
    name3,
    name_max
};

char *name[name_max]={"name1","name2","name3"};
char *score1[name_max]={"12","11","1"};
char *score2[name_max]={"1","13","22"};


int main(void)
{
    int line;

    printf("Number\tPlayer Name\tScore\n");
    printf("\t\tGame1\tGame 2\n");

    for (line=name1;line < name_max;line++)
    {
        printf("%d\t%s\t%s\t%s\n", line+1, name[line], score1[line], score2[line]);
    }

    getchar();
    return 0;   
}

得到以下结果:

enter image description here

答案 1 :(得分:0)

要使用相同的编码风格回答,您可以将循环嵌套为:

    for (i=0;i<PLAYERS;i++)
    {
        printf("%10s\n", player[i]);

        for (x=1; x<=PLAYERS; x++)
        {
            printf("score %d:\t", x);
            for (j=0 ;j<GAME; j++)      // << notice J not I
            {
               fgets(scorex[j], LENGTH, stdin);
            } // end for j = 0

            printf("%5s\n", scorex[i]);

        }  // end for x=1

    }  // end for i = 0

请注意。我没有调试你的代码,只是写了嵌套for循环,你需要做更多的工作。其中一个错误可能是使用i作为内循环和外循环。

相关问题