所以我有这个代码:
#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
人中查找最年长的人。我想将 5
人更改为 N
人,无论我自己输入多少人。 (例如我输入7
,我可以插入七个名字和年龄等等)。
最佳答案
问题有两部分:用户如何指定输入多少人?我如何存储数据?
第二部分很简单:无论你要考虑多少人,如果你只想知道谁是最年长的,那么保留当前最年长的人的姓名和年龄就足够了。 (当然,如果有平局,而且很多人都80岁了,你就可以保留第一场比赛。)
不存储任何内容也简化了第一个问题。您可以要求用户事先指定人数,如果人数很少,则可以找到。如果您有很多人的列表,用户将必须手动计数,然后输入计数。错误计数的可能性很大。
更好的方法是通过其他方式指示输入的结束,例如通过负年龄或两个破折号作为名称。输入也有可能用完,例如,当从文件重定向输入时,或者在输入后按 Ctrl-Z 或 Ctrl-D 之一(具体取决于您的平台)时。
下面的示例按行读取输入,然后扫描该行。循环 while (1)
理论上是无限的,实际上,当输入用完时,执行就会跳出循环 – fgets
return NULL
– ,当读取空行或输入的格式不是单字姓名和年龄时。
#include <stdio.h>
int main(void)
{
char oldest[80] = "no-one";
int max_age = -1;
int count = 0;
puts("Enter name & age on each line, blank line to stop:");
while (1) {
char line[80];
char name[80];
int age;
if (fgets(line, sizeof(line), stdin) == NULL) break;
if (sscanf(line, "%s %d", name, &age) < 2) break;
if (age > max_age) {
strcpy(oldest, name);
max_age = age;
}
count++;
}
printf("The oldest of these %d people is %s, aged %d.\n",
count, oldest, max_age);
return 0;
}
关于c - 通过 N 个输入查找 C 中最大的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33152150/