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
但是,如果一个月中的两天温度相同怎么办?
我猜屏幕会显示 first/older 温度:
Day 1 = 23
Day 2 = 33
Day 3 = 33
Day 4 = 30
Day 5 = 33
在这种情况下,第 2 天。
如何让它打印最近的最高温度(上例中的第 5 天)?
使用:
if (april[i] >= max)
如果温度等于当前最大值,这将保存位置,因此您将拥有该温度的最后一天。
在你的代码中
if(april[i]>max)
必须改为
if(april[i]>=max)
原因 是,在第一种情况下,一旦通过输入 if
语句分配最大值,再次重复相同的值时,它不会进入 if block as max > max 为 false 但在第二种情况下 max>=max 为 true,编译器将进入 if 块并更新其值。
直接写
if (april[i] >= max) instead of if (april[i] > max)
这将找到最大值和最近的一个,我的意思是最后一个,因为它正在检查即将到来的索引值是否与前一个相同或大于前一个,如果只是更新最大值。
在一组温度中,整个月的每一天:
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
但是,如果一个月中的两天温度相同怎么办? 我猜屏幕会显示 first/older 温度:
Day 1 = 23
Day 2 = 33
Day 3 = 33
Day 4 = 30
Day 5 = 33
在这种情况下,第 2 天。
如何让它打印最近的最高温度(上例中的第 5 天)?
使用:
if (april[i] >= max)
如果温度等于当前最大值,这将保存位置,因此您将拥有该温度的最后一天。
在你的代码中
if(april[i]>max)
必须改为
if(april[i]>=max)
原因 是,在第一种情况下,一旦通过输入 if
语句分配最大值,再次重复相同的值时,它不会进入 if block as max > max 为 false 但在第二种情况下 max>=max 为 true,编译器将进入 if 块并更新其值。
直接写
if (april[i] >= max) instead of if (april[i] > max)
这将找到最大值和最近的一个,我的意思是最后一个,因为它正在检查即将到来的索引值是否与前一个相同或大于前一个,如果只是更新最大值。