简体   繁体   English

C:最近的最大数组值

[英]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. 在这种情况下,第2天

How can I make it print the latest, most recent maximum temperature (Day 5 in the example above)? 如何使它打印最新的最新最高温度(以上示例中的第5天)?

Use: 采用:

if (april[i] >= max)

which will save the position if temp equals current maximum, so you will have last day with that temperature. 如果temp等于当前的最大值,它将保存位置,因此您将拥有该温度的最后一天。

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. 原因是,在第一种情况下,一旦通过输入if语句分配了最大值, if再次重复相同的值时,它将不会输入if块,因为max> max为false,而在第二种情况下为max> = max为true,编译器将输入if块并更新其值。

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. 这将找到最大值,也将是最近的值,我的意思是最后一个值,因为它正在检查即将到来的索引值是否等于或大于前一个索引值,如果是,则更新最大值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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