例2.1 求1·2·3·4·5
#include <stdio.h>
int main()
{
int i, f=1;
printf("1");
for(i = 2; i <= 5; i ++)
{
printf("×%d", i);
f*=i;
}
printf("=%d\n", f);
return 0;
}
运行结果如下
例2.3 判断2000-2500年终的每一年是否为闰年,并将结果输出
#include<stdlib.h>
int main()
{
int year,leap;
for(year = 2000; year <= 2500; year++)
{
leap=((year%4==0&&year%100!=0)||(year%400==0))?1:0 ;
if(leap) printf("%d is a leap year.\n",year);
}
return 0;
}
运行结果如下
例2.4求1-1/2+1/3-1/4+···+1/99-1/100
#include<stdio.h>
int main()
{
int sign=1;
double deno=2.0,sum=1.0,term;
while (deno<=100)
{
sign=-sign;
term=sign/deno;
sum=sum+term;
deno=deno+1;
}
printf("%f\n",sum);
return 0;
}
运行结果如下