查找数组中列中的最大数字

时间:2014-08-12 10:02:42

标签: c++ arrays numbers

第一个源文件

#include<stdio.h>
void main(void)
{
    extern int transitTime[];
    int time1;
    int i,j;
    int largest;
    printf("Please enter time leaving school.\n");
    scanf("%d",&time1);
    for(i=0;i<time1;i++)
    {
    largest=0;
    printf("The longest travelling time ");

    for(j=0;j<4;j++)
    {
    //printf("%d ",transitTime[i+j*11]);
    if(transitTime[i+j*11]>largest)largest=transitTime[i+j*11];
    }

    printf("is %d\n",largest);
    }
}

第二个源文件

int transitTime[] ={
 56,58,57,52,54,53,48,49,51,57,62, //bus 8
 39,43,40,34,37,36,31,32,42,49,59, //bus15
 42,47,43,42,51,49,40,41,48,50,58, //22
 50,55,51,49,52,47,49,48,53,41,55, //23
 };

调试程序后的输出是

Please enter the time leaving school
5
The longest time is 56
The longest time is 58
The longest time is 57
The longest time is 52
The longest time is 54

如何让程序选择我想要的行:

Please enter the time leaving school
5
The longest time is 54

提前致谢!!

1 个答案:

答案 0 :(得分:0)

以这种方式更改您的代码

void main(void)
{
    extern int transitTime[];
    int time1;
    int i,j;
    int largest;
    printf("Please enter time leaving school.\n");
    scanf("%d",&time1);
//    for(i=0;i<time1;i++)
//    {
    i = time1 - 1;
    largest=0;
    printf("The longest travelling time ");

    for(j=0;j<4;j++)
    {
    //printf("%d ",transitTime[i+j*11]);
    if(transitTime[i+j*11]>largest)
                largest=transitTime[i+j*11];
    }

    printf("is %d\n",largest);
 //   }
}

不需要使用i变量进行循环。

只需选择i的值time1 -1

即可