我想编写一个函数来帮助用户插入 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/