第二章 算法-程序的灵魂
例2.1求五的阶乘
#include <stdio.h>
int main()
{
int i = 1, j;
for ( j = 1; j < 6; j++ )
i = i * j;
printf( “5!=%d\n”, i );
}
运行结果为:
例2.3 判定2000-2500年中的每一年是否为闰年,并将结果输出。
#include <stdio.h>
int main()
{
int i;
for ( i = 2000; i <= 2500; i++ )
if ( i % 4 = 0 && i % 100 != 0 || i % 400 = 0 )
printf( “%d\t”, i );
else
continue;
}
运行结果如下:
例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 += term;
deno += 1;
}
printf( “输出结果为:%f\n”, sum );
}
运行结果如下:
课后习题1 依次输入十个数,输出最大值
#include <stdio.h>
int main()
{
int n = 1, max, a;
printf( “输入十个数:” );
while ( n <= 10 )
{
scanf( “%d”, &a );
if ( a > max )
max = a;
n++;
}
printf( “max=%d\n”, max );
}
课后习题2 三个数从小到大输出
#include <stdio.h>
int main()
{
int a, b, c, t;
printf( “输入三个数:” );
scanf( “%d%d%d”, &a, &b, &c );
if ( a > b )
{
t = a;
a = b;
b = t;
}
if ( a > c )
{
t = a;
a = c;
c = t;
}
if ( b > c )
{
t = b;
b = c;
c = t;
}
printf( “%d %d %d\n”, a, b, c );
}
运行结果如下:
课后习题3 求1+2+3····+100
#include <stdio.h>
int main()
{
int i, sum = 0;
for ( i = 1; i <= 100; i++ )
sum = sum + i;
printf( “结果为:%d\n”, sum );
}
运行结果如下:
课后习题4 判断一个数能否同时被三和五整除
#include <stdio.h>
int main()
{
int i;
printf( “输入一个数:” );
scanf( “%d”, &i );
if ( i % 3 == 0 && i % 5 == 0 )
printf( “\n能同时被整除\n” );
else
printf( “\n不能同时被整除\n” );
}
运行结果如下:
##课后习题5 将100到200之间的素数输出
#include <stdio.h>
int main()
{
int i,j;
int count=0;
for (i=101; i<=200; i++)
{
for (j=2; j<i; j++)
{ if (i%j==0) break;
}
if (j>=i)
{
count++; printf("%d ",i);
if (count % 5 == 0)
printf("\n");
}
}
}
运行结果如下:
课后习题6 求两个数m和n的最大公约数
#include <stdio.h>
int main()
{
int m, n, t;
printf( “输入两个数:” );
scanf( “%d%d”, &m, &n );
if ( m < n )
{
t = n;
n = m;
m = t;
}
t = m % n;
while ( t != 0 )
{
m = n;
n = t;
t = m % n;
}
printf( “最大公约数为%d\n”, n );
}
运行结果如下: