首页 > 解决方案 > 停止数组在末尾打印 0

问题描述

我做了一个猜谜游戏,其中生成了一个随机数,用户有 10 次尝试猜测它。在游戏结束时,程序打印所有尝试的数组。当用户在少于 10 次尝试中正确猜测时,数组打印出所有尝试并在之后打印零,这样由于 for 循环,总共有 10 个元素。

如果数字是 62 并且它在 6 次尝试中被猜到,例如它看起来像

Your Tries: 50 90 60 65 63 62 0 0 0 0

我想让它在游戏结束时不打印额外的零。

#include <stdio.h>
#include <time.h>
#include <stdlib.h>

int main (int argc, char** argv)
{
  int s, n, v, win = 0, lose = 0;
  char c;

  srand( time(NULL) );
  s = rand () % 100 + 1;

  int tries = 0;
  int a[n];

  for (tries = 0; tries < 10; tries++)
    {
      scanf ("%d", &a[tries]);

      if (a[tries] == s)
    {
      win++;
      printf ("\nYou win!\n");
      printf ("Your Tries: ");
      for (tries = 0; tries < 10; tries++)
        {
          printf ("%d ", a[tries]);
        }
      printf ("\nTry Again? ");
      scanf (" %c", &c);
      if (c == 'n' || c == 'N')
        {
            printf("Your stats: %d Win, %d Lose", win, lose);
          return 0;
        }
      if (c == 'y' || c == 'Y');
      {
        tries = 0;
        s = rand () % 100 + 1;
        scanf ("%d", &a[tries]);
      }
    }

      printf ("The number is %s %d.\n", a[tries] > s ? "less than" : "greater than",
          a[tries]);
    }
    
  printf ("You input wrong number. You lose. The number is %d.\n", s);
  lose++;
  printf ("Your Tries: ");
    for (tries = 0; tries < 10; tries++)
        printf ("%d ", a[tries]);

        printf ("\nTry Again? ");
        scanf (" %c", &c);
  if (c == 'n'|| c == 'N')
    {
         printf("Your stats: %d Win, %d Lose", win, lose);
        return 0;
    }
  if (c == 'y' || c == 'Y');
  {
        tries = 0;
        s = rand () % 100 + 1;
        scanf ("%d", &a[tries]);
  }
}

标签: arraysc

解决方案


看起来您使用以下命令打印出最后十个数字:

for (tries = 0; tries < 10; tries++) {
   printf ("%d ", a[tries]);
}

但是,即使您的数字少于十个,它也会继续循环,一个简短的解决方法是添加一个变量来存储尝试次数,每次尝试增加它,然后在 for 循环中使用它以不打印太多数字:

int tries = 0;
int nb_tries = 0;
int a[n];

for (tries = 0, nb_tries = 0; tries < 10; tries++, nb_tries++) {
   scanf("%d", &a[tries]);
   if (a[tries] == s) {
      win++;
      printf ("\nYou win!\n");
      printf ("Your Tries: ");
      for (tries = 0; tries < nb_tries; tries++) {
         printf("%d", a[tries]);
      }
   }
}

推荐阅读