2015-10-15 34 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 
} 

見我的意見進行說明。事實上,你的代碼中有一些問題,所以我修復了它們。

相關問題