【问题标题】:C: Most recent maximum array valueC:最近的最大数组值
【发布时间】:2015-12-06 18:10:54
【问题描述】:

在一系列温度中,整月的每一天:

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 天)?

【问题讨论】:

  • 注意,4 月有 30 天,而不是 31 天。使用 int month[31]; 会更容易混淆。
  • 作为一种风格,而不是for(i=0; i&lt;=days-1; i++),请编码为for(i=0; i&lt;days; i++)。更清楚了,如果你继续这样下去,当你有unsigned days = 0;时,你最终会掉进一个洞里,这在分析数据时很容易发生。
  • 我只是在试验,这段代码没什么大不了的,但是感谢您的观察,它真的很有帮助。

标签: c arrays max


【解决方案1】:

用途:

if (april[i] >= max)

如果温度等于当前最大值,它将保存位置,因此您将在该温度下度过最后一天。

【讨论】:

    【解决方案2】:

    在您的代码中

    if(april[i]&gt;max)

    必须改为

    if(april[i]&gt;=max)

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

    【讨论】:

    • 只是一个提示:您可以将 if 块放在上面的 for 循环中,用于打印日期及其温度@Coursal
    【解决方案3】:

    简单写

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

    这将找到最大值以及最近的一个,我的意思是最后一个,因为它正在检查即将到来的索引值是否与前一个相同或更大,如果是,则更新最大值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-28
      • 2017-02-13
      • 2011-02-25
      • 1970-01-01
      • 2013-10-28
      • 1970-01-01
      • 2016-10-06
      • 2016-09-10
      相关资源
      最近更新 更多