C语言常用算法总结教学教案.ppt演示文稿演讲PPT学习教学课件医学文件教学培训课件
常用算法总结
(1)分段函数的计算:4-1.C
(2)多项式累加和、累乘积:5-1.C
(3)求素数(判断素数):8-1.C
(4)数的分解,如水仙花数,完数等:5-2.C(完数)
(5)数组运算,如找最大,最小值问题,累加和,求平均值:7-1.C、7-2.C
(6)排序运算,如冒泡法,选择排序:6-1-1.C,6-1-2.C
(7)字符串操作:strcpy, strcat ,strlen:6-2.C(strcat函数)
4-1.C
#include
main()
{
int x, y;
scanf("%d", &x);
if(x<1)
{
y=x;
printf("x=%3d, y=x=%d\n",x,y);
}
else
if(x<10)
{
y=2*x-1;
printf("x=%3d, y=2*x-1=%d\n",x,y);
}
else
{
y=3*x-11;
printf("x=%3d, y=3*x-11=%d\n",x,y);
}
}
5-1.C
#include
main()
{
int i, t = 1, sum = 0;
for( i=1; i<=5; i++)
{
t = t * i;
sum += t;
}
printf( "%d" , sum );
}
8-1.C
#include "stdio.h"
int fun( int n ) /*返回: 1:素数, 0:非素数 */
{
int i;
for( i = 2; i < n; i++)
if( n%i == 0 ) return 0;
return 1;
}
main( )
{
long a=0;
int k,count=0;
float av;
for( k=2; k <= 1000; k++)
if( fun(k) )
{
a += k;
count++;
}
av = 1.0*a / count;
printf( "av = %.2f \n", av );
}
5-2.C
#include
main()
{
int i, j, s = 0;
for( i = 1; i < 1000; i++)
{
for ( j = 1; j < i; j++ )
if( i%j ==0 ) s += j;
if( i == s )
{
printf( "%d its factors are 1", i );
for( j = 2; j < i; j++ )
if( i % j == 0 ) printf( ",%d", j );
printf("\n");
}
s = 0;
}
}
6-1-1.C
#include
#define N 10
main()
{
int a[N], i, j, temp;
printf( "please input %d numbers\n", N);
for( i=0; i
for( i = 0; i < N - 1; i++ )
for( j = 0; j < ( N -i )- 1; j++)
{
if( a[j] > a[j+1] )
{
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
printf( "the array after sort:\n" );
for( i = 0; i < N; i++