c - 求 C 语言中最大的数字,但带有字符

标签 c arrays data-structures char numbers

我想编写一个函数来帮助用户插入 N 个人及其姓名和年龄。

例如:

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

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

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]);
}

关于c - 求 C 语言中最大的数字,但带有字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33150587/

相关文章:

arrays - 如何将元组添加到 Swift 数组?

arrays - 如何在 Autohotkey 中发送数组变量的值?

c# - 使用多个键创建字典并使用其中一个键获取值

用于处理 2D 点、数组、列表或其他的 Java 数据结构?

连接字符串并将它们存储在 ANSI C 的缓冲区中

将 void* 转换为 double

MySQL C API : Getting `MYSQL_FIELD` array from `MYSQL_STMT` ?

javascript - JavaScript 的 array.clear() 不是函数吗?

c++ - 交换指针数组(指向类的指针)元素

c - recv() 的原型(prototype)