我想编写一个函数,帮助用户插入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人(我的意思是,我如何选择我可以输入的人数)?
答案 0 :(得分:2)
您需要询问用户他们想要插入的号码。 一旦给出这个,你需要设置数组的大小,因为直到之后你才知道它们的大小
#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]);
}
答案 1 :(得分:1)
这应该是你想要的:
#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
}
请参阅我的评论。事实上,您的代码中存在一些问题,因此我修复了它们。
答案 2 :(得分:0)
我做了一些改动,但是我认为以一种更简单的方式查看将有所帮助。
#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;
}