2015-10-15 50 views
-28

我想编写一个帮助用户插入N个人的函数,它们的名字和年龄。查找C中最大的数字,但是带有字符

例如:

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人(我的意思是,我如何选择可以输入的人数)?

+10

我投票结束这个问题作为题外话,因为SO是没有家庭作业服务。 – Olaf

+4

SO不是您的家庭作业的个人服务 – Magisch

+3

好的,我们确实知道您**想要** ..而问题是? – Michi

回答

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

这应该是你想要什么:

#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 
} 

见我的意见进行说明。事实上,你的代码中有一些问题,所以我修复了它们。