簡體   English   中英

C:最近的最大數組值

[英]C: Most recent maximum array value

在一系列溫度下,每天一個月的時間:

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 maximum temperature is 42 on Day 2 of the month

但是,如果一個月中的兩天溫度相同怎么辦? 我猜屏幕會顯示第一個/更舊的溫度:

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

在這種情況下,第2天

如何使它打印最新的最新最高溫度(以上示例中的第5天)?

采用:

if (april[i] >= max)

如果temp等於當前的最大值,它將保存位置,因此您將擁有該溫度的最后一天。

在您的代碼中

if(april[i]>max)

必須更改為

if(april[i]>=max)

原因是,在第一種情況下,一旦通過輸入if語句分配了最大值, if再次重復相同的值時,它將不會輸入if塊,因為max> max為false,而在第二種情況下為max> = max為true,編譯器將輸入if塊並更新其值。

只需寫

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

這將找到最大值,也將是最近的值,我的意思是最后一個值,因為它正在檢查即將到來的索引值是否等於或大於前一個索引值,如果是,則更新最大值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM