简体   繁体   中英

C: Most recent maximum array value

In an array of temperatures, each day for a whole month:

int april[31];
    int days;
    int i=0, maxpos, max;

    printf("How many days are in this month?\n");
    scanf("%d", &days);

    if (days < 0)
       printf("Unreceivable number of days\n");
    else{

         for(i=0; i <= days-1; i++)
         {
             printf("Day %d: Give today's temperature: \n", i+1);
             scanf("%d", &april[i]);
         }

         for(i=0; i <= days-1; i++)
             printf("%Day %d  = %d\n", i+1, april[i]);  

         maxpos=0; 
         max = april[0];   

         for(i=0; i <= days-1; i++)
         {
              if (april[i] > max)
              {
                 max = april[i];
                 maxpos = i;
              }
         }  

         printf("The maximum temperature of the month is %d on Day %d of the month\n", max, maxpos+1);

     }

the programme has to print out the maximum temperature and the day that happened, like:

The maximum temperature is 42 on Day 2 of the month

But, what if two days of the month have the same temperature? I guess the screen will show the first/older temperature:

Day 1 = 23
Day 2 = 33
Day 3 = 33
Day 4 = 30
Day 5 = 33

in this case, Day 2.

How can I make it print the latest, most recent maximum temperature (Day 5 in the example above)?

Use:

if (april[i] >= max)

which will save the position if temp equals current maximum, so you will have last day with that temperature.

Here in your code

if(april[i]>max)

must be changed to

if(april[i]>=max)

the reason being that, in first case once max value gets assigned by entering the if statement, once again when same value is repeated it wont enter the if block as max > max is false but in second case as max>=max is true, compiler would enter the if block and update its value.

Simply write

if (april[i] >= max) instead of if (april[i] > max)

this will find the maximum and also the recent one i mean the last one as it is checking whether the coming index value is same or bigger than the previous one if so just update the max.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM