通过使用Duff 的设备,您可以在 for 循环中保存一些比较。这是一个不好的做法,但也许这就是你应该做的。
#include <stdio.h>
int main (void) {
unsigned max = 0;
unsigned length;
scanf("%u", &length);
unsigned temp = 0;
unsigned iterations = (length+8-1) / 8;
switch (length % 8) {
case 0: do { scanf("%u", &temp); if (temp > max) max = temp;
case 7: scanf("%u", &temp); if (temp > max) max = temp;
case 6: scanf("%u", &temp); if (temp > max) max = temp;
case 5: scanf("%u", &temp); if (temp > max) max = temp;
case 4: scanf("%u", &temp); if (temp > max) max = temp;
case 3: scanf("%u", &temp); if (temp > max) max = temp;
case 2: scanf("%u", &temp); if (temp > max) max = temp;
case 1: scanf("%u", &temp); if (temp > max) max = temp;
} while (--iterations > 0);
}
printf("%u\n", max);
return 0;
}
我使用unsigned
整数,因为你说你只有正数。代码假定序列至少有一个元素。
更新1:
使用手动循环展开的示例。这比达夫的设备还要糟糕。也许你得到的测试工具会喜欢它,但你永远不应该使用这个代码来打动潜在的雇主!
#include <stdio.h>
int main (void) {
signed max = -0x80000000;
unsigned length;
scanf("%u", &length);
signed temp;
for (; length >= 8; length -= 8) {
scanf("%d", &temp); if (temp > max) max = temp;
scanf("%d", &temp); if (temp > max) max = temp;
scanf("%d", &temp); if (temp > max) max = temp;
scanf("%d", &temp); if (temp > max) max = temp;
scanf("%d", &temp); if (temp > max) max = temp;
scanf("%d", &temp); if (temp > max) max = temp;
scanf("%d", &temp); if (temp > max) max = temp;
scanf("%d", &temp); if (temp > max) max = temp;
}
if (length > 4) {
scanf("%d", &temp); if (temp > max) max = temp;
scanf("%d", &temp); if (temp > max) max = temp;
scanf("%d", &temp); if (temp > max) max = temp;
scanf("%d", &temp); if (temp > max) max = temp;
length -= 4;
}
for (; length > 0; --length) {
scanf("%d", &temp); if (temp > max) max = temp;
}
printf("%d\n", max);
return 0;
}
更新 2:
您说如果 scanf 不常被调用,您的评估工具会喜欢它,所以:
#include <stdio.h>
int main (void) {
signed max = -0x80000000;
unsigned length;
scanf("%u", &length);
signed t1, t2, t3, t4, t5, t6, t7, t8;
for (; length >= 8; length -= 8) {
scanf("%d%d%d%d%d%d%d%d", &t1, &t2, &t3, &t4, &t5, &t6, &t7, &t8);
if (t1 > max) max = t1;
if (t2 > max) max = t2;
if (t3 > max) max = t3;
if (t4 > max) max = t4;
if (t5 > max) max = t5;
if (t6 > max) max = t6;
if (t7 > max) max = t7;
if (t8 > max) max = t8;
}
if (length > 4) {
scanf("%d%d%d%d", &t1, &t2, &t3, &t4);
if (t1 > max) max = t1;
if (t2 > max) max = t2;
if (t3 > max) max = t3;
if (t4 > max) max = t4;
length -= 4;
}
for (; length > 0; --length) {
scanf("%d", &t1); if (t1 > max) max = t1;
}
printf("%d\n", max);
return 0;
}