为什么相同的循环体次数,for循环明显更快执行完毕?
include <reg51.h
void delay(void)
{
//while循环方式
unsigned char i=200;
unsigned char j=20
因为两份代码并不等价
根据题主的代码写一个 test:
#include <stdio.h>
void delay_while() {
puts("while:");
unsigned char i = 200;
unsigned char j = 200;
while (i--)
while(j--)
printf("%d %d\n", i, j);
}
void delay_for() {
puts("for:");
unsigned char i = 200;
unsigned char j = 200;
for (i = 200; i > 0; i--)
for(j = 200; j > 0; j--)
printf("%d %d\n", i, j);
}
int main() {
freopen("while.out", "w", stdout);
delay_while();
freopen("for.out", "w", stdout);
delay_for();
return 0;
}
int main() {
delay_while();
delay_for();
return 0;
}
输出文件中,while.out
有 50947
行,for.out
有 40002
行。