三種 loop
(高顯忠, sjgau4311@gmail.com, 2011-01-20 07:18)
1樓
#if 0
of for loop, no= 2000000000, sum= -1973237248, xsum= 2000000001000000000.000, i
= 2000000001
of while loop, no= 2000000000, sum= -1973237248, xsum= 2000000001000000000.000,
i= 2000000001
of do, no= 2000000000, sum= -1973237248, xsum= 2000000001000000000.000, i= 2000
000001
Press any key to continue
#endif
// --------------------------------------------------------
#include <stdio.h>
#include <stdlib.h>
// --------------------------------------------------------
main()
{
int no, sum, i;
double xsum;
// loop of for ... next
no= (int) (20E+8 + 0.5);
sum= 0;
for (i=1;i<=no;i++) {
sum= sum + i;
}
xsum= (1.0 + no)*(no - 1.0 + 1)/2.0;
printf("\n of for loop, no= %d, sum= %d, xsum= %.3lf, i= %d\n",
no, sum, xsum, i);
// system("pause");
// ----------------------------------------------------
// loop of while ... do
sum= 0;
i= 1;
while (i <= no) {
sum+= i;
i++;
}
xsum= (1.0 + no)*(no - 1.0 + 1)/2.0;
printf("\n of while loop, no= %d, sum= %d, xsum= %.3lf, i= %d\n",
no, sum, xsum, i);
// system("pause");
// ----------------------------------------------------
// loop of do
sum= 0;
i= 1;
do {
sum+= (i++);
} while (!(i > no));
xsum= (1.0 + no)*(no - 1.0 + 1)/2.0;
printf("\n of do, no= %d, sum= %d, xsum= %.3lf, i= %d\n",
no, sum, xsum, i);
// system("pause");
// system("pause");
return 0;
}