繁体   English   中英

在 C 中找到最大的数字,但有字符

[英]Find the Biggest Number in C, BUT with characters

我想编写一个函数来帮助用户插入 N 个人,包括他们的姓名和年龄。

例如:

4
John Williams 37
Michael Douglas 65
Will Smith 51
Clark Kent 33

然后,我必须根据age找到最旧的并打印姓名和年龄:

Michael Douglas 65

编辑:

我有一个新代码,这是一个:

#include <stdio.h>
int main()
{
  char peopleName[5][20],peopleAge[5];
  int i;
  int maxAge=0, maxName=-1;
  for(i=0;i<5;i++)
  {
    printf("Name & Age %d :",i+1);
    scanf("%s",&peopleName[i]);
    scanf("%d",&peopleAge[i]);
    if(peopleAge[i]>maxAge)
    {
      maxAge=peopleAge[i];
      maxName=i;
    }
  }
  printf("%s %d", peopleName[maxName],peopleAge[maxAge]);
}

我的问题是:如何从 5 人变成 N 人(我的意思是,我如何选择可以输入的人数)?

您需要向用户询问他们想要插入的号码。 一旦给出这个,你需要设置数组的大小,因为直到之后你才知道它们的大小

#include <stdio.h>

int main() {
  int i;
  int maxAge = 0, maxName = -1;
  int numberOfPeople = 0;
  scanf("%d", & numberOfPeople);
  //now we have to set the arrays to the size that we are inserting
  char peopleName[numberOfPeople][20], peopleAge[numberOfPeople];

  for (i = 0; i < numberOfPeople; i++) {
    printf("Name & Age %d :", i + 1);
    scanf("%s", & peopleName[i]);
    scanf("%d", & peopleAge[i]);
    if (peopleAge[i] > maxAge) {
      maxAge = i; //you had the actual age here, 
      //but you need the index of the highest age instead
      maxName = i;
    }
  }
  printf("%s %d", peopleName[maxName], peopleAge[maxAge]);
}

这应该是你想要的:

#include <stdio.h>

#define MAX_PEOPLE 100
#define MAX_NAME 100 

int main(void)
{
    char peopleName[MAX_PEOPLE][MAX_NAME];
    int peopleAge[MAX_PEOPLE]; // a person's age is an integer
    int n, i;
    int maxAge = 0, maxName = -1;
    puts("How many people do you want to input?");
    scanf("%d%*c", &n); // discarding '\n'
    if(n > MAX_PEOPLE)
        puts("Too many people!");
    for(i = 0; i < n; i++)
    {
        printf("Name & Age %d :", i + 1);
        scanf(" %s", peopleName[i]);
        scanf(" %d", &peopleAge[i]); // discarding whitespace characters
        if(peopleAge[i] > maxAge)
        {
            maxAge = peopleAge[i];
            maxName = i;
        }
    }
    printf("%s %d", peopleName[maxName], maxAge); // maxAge is a value, rather than an index
}

请参阅我的评论以获取说明。 事实上,你的代码中存在一些问题,所以我修复了它们。

我改变了一点,但我认为以更简单的方式查看会有所帮助。

#include <stdio.h>

int main(void) {
  int indexOfMaxAge = 0, numberOfPeople = 0;

  scanf("%d", &numberOfPeople);

  char peopleName[numberOfPeople][20], peopleAge[numberOfPeople];

  for (int i = 0; i < numberOfPeople; i++) {
    printf("Name & Age %d :", i + 1);
    scanf("%s", &peopleName[i]);
    scanf("%d", &peopleAge[i]);
    if (peopleAge[i] > peopleAge[indexOfMaxAge]) indexOfMaxAge = i;
    // only the index of the older person
    // is being stored and used to compare
  }
  printf("%s %d\n", peopleName[indexOfMaxAge], peopleAge[indexOfMaxAge]);

  return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM