循环只运行一次:while和for(c)

时间:2017-03-03 22:03:23

标签: c

void abScores()
{
int i, choice, abScore[6], abScoreTwo[6];
char abS[6][5] = {"Str", "Dex", "Con", "Int", "Wis", "Cha"};
FILE *fp;
FILE *fo;
fp = fopen("csheet.txt", "a");

printf("Would you like your own ability scores, or the basic ability scores?\n");
printf("1 for own, 2 for basic\n");
scanf("%d", &choice);

if (choice == 1)
{
    for (i = 0; i < 6; i++)
    {
        abScore[i] = roll();
        printf("Ability score %d: %d\n", i+1, abScore[i]);
    }
}
else if (choice == 2)
{
    abScore[0] = 15;
    abScore[1] = 14;
    abScore[2] = 13;
    abScore[3] = 12;
    abScore[4] = 10;
    abScore[5] = 8;
    for (i = 0; i < 6; i++)
        printf("Ability score %d: %d\n", i+1, abScore[i]);
}

i = 0;
while (i < 6)
{
    printf("What score would you like for %s?\nPlease use each score only once.\n", abS[i]);
    for (i = 0; i < 6; i++)
    {
        printf("%2d\n", abScore[i]);
    }
    //scanf("%d", &abScoreTwo[i]);
    i++;
}

for (i = 0; i < 6; i++)
    fprintf(fp, "%s: %d\n", abS[i], abScoreTwo[i]);
}

在主函数中运行时,此循环似乎只运行一次。我也尝试将它作为for循环运行,但它只运行一次。谁能告诉我为什么会这样?该函数应该从一个名为roll()的函数中获取输入,该函数将六面骰子滚动到数组中的四个位置,将它们相加,得到最低,然后从总和中减去最低值,然后将其放入数组中在abScores()函数中。它只运行一次,但我希望它运行六次以使该功能实际工作。

3 个答案:

答案 0 :(得分:6)

您在两个循环中重复使用i

while (i < 6)
{
    printf("What score would you like for %s?\nPlease use each score only once.\n", abS[i]);
    for (i = 0; i < 6; i++)

内部for循环也会更改外部i循环的while值,并在第一次迭代时退出。考虑使用2个单独的变量

答案 1 :(得分:2)

您在while循环中的i循环内重用for。 for循环完成后,i将设置为6,因此会破坏循环条件。

答案 2 :(得分:1)

在内部循环中创建一个新变量,这是一种很好的做法,例如(将i更改为j):

while (i < 6)
{
    printf("What score would you like for %s?\nPlease use each score only once.\n", abS[i]);
    for (int j = 0; j < 6; j++)
    {
        printf("%2d\n", abScore[j]);
    }
    //scanf("%d", &abScoreTwo[i]);
    i++;
}

另一个好的做法是为您的变量提供更有意义的名称,而不是ij