0

这是一个家庭作业问题。我有一个 C 程序,它接受用户输入许多人的名字、姓氏和年龄。现在它可以正常工作并将名称正确打印到控制台,但它没有打印出正确的年龄,我无法弄清楚我做错了什么。这是我的代码:

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

int main()
{
    int choice;
    int i = 0;
    int x,k,l;
    fputs("How many people would you like to add? ", stdout);
    scanf(" %d", &choice);
    fflush(stdout);

    int ch;
    while((ch = getchar()) != EOF && ch != '\n');
    if (ch == EOF) 
    {
    }

    char firstName[choice][20];
    char lastName[choice][20];
    int age[choice][3];

    char first[20];
    char last[20];
    int a[3];

    for (x = 0; x < choice; x++) 
    {
        for (l = 0; l < 3; l++)
        {
            age[x][l] = 0;
            a[l] = 0;
        }
    }


    while(i < choice)
    {
      printf("Enter the first name of person ");
      printf(" %d", i);
      printf(": ");
      fgets(first, 20, stdin); 

      for (k = 0; k < 20; k++)
      { 
        firstName[i][k] = first[k];
      }
      i++;
    } 

    i = 0;
    while(i < choice)
    {
      printf("Enter the last name of person ");
      printf(" %d", i);
      printf(": ");
      fgets(last, 20, stdin);     

      for (k = 0; k < 20; k++)
      { 
          lastName[i][k] = last[k];
      }
      i++;
    } 

    i = 0;

    while(i < choice)
    {
      fputs("Enter the age of person ", stdout);
      printf(" %d", i);
      printf(": ");
      scanf(" %d", &a);
      fflush(stdout);

      for (l = 0; l < 3; l++)
      { 
          age[i][l] = a[l];
      }
      i++;
    }

    int sh;
    while((sh = getchar()) != EOF && sh != '\n');
    if (sh == EOF) 
    {
    }

    for (x = 0; x < choice; x++) 
    {
      printf("First name ");
      printf(": ");
      printf("%s ", firstName[x]);
      printf("\n");
      printf("Last name ");
      printf(": ");
      printf("%s ", lastName[x]);
      printf("\n");
      printf("Age ");
      printf(": ");
      printf("%d ", &age[x]);
      printf("\n");
    }
    return 0;
}

如果您复制/粘贴此代码,它将运行,但输出的年龄将不正确。谁能告诉我这是为什么?谢谢!

4

1 回答 1

2

scanf("%d", &a);

那应该是:

scanf("%d", &a[0]);

printf应该是printf("%d", age[x][0]);

您想读入数组的第一个元素,而不是整个数组。您想打印出数组的第一个元素,而不是数组的地址。

更好的解决方案可能是根本不制作age3 的数组。每个人只有一个年龄。更改将是:

int age[choice];

int a;

scanf(" %d", &a);

age[choice] = a;

printf("%d ", age[x]);
于 2013-04-29T23:17:19.827 回答