我会把我学习C语言碰到的经典的算法题目全都归类到这个帖子中,希望对和我一样学习编程的小白有帮助!但求精简,以最少的时间入门C语言。
1.输入n个数,输出其中最大的一个数。
#include <stdio.h>
int main()
{
int n,i,s=0; //s为最大的数
int a[100]; //存储的数组
printf("请输入你要比较的个数:");
scanf("%d", &n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
if(s<a[i]) s=a[i];
}
printf("最大值是:%d\n",s);
}
#include<stdio.h> int main() { double a=2, b=1, sign=1; while(a<=100) { sign = -sign; b = sign/a + b; a = a + 1; } printf("sum = %lf\n",b); return 0; }
//方法1 #include <stdio.h> int main() { int max(int x, int y); int a, b, c, d, e; scanf("%d, %d, %d", &a, &b, &c); d = max( a, b ); e = max( d, c ); printf("max = %d\n", e); } int max(int x, int y) { int z; if(x>y) z = x; else z = y; return(z); }
//方法2 #include <stdio.h> int main() { int a,b,c,max; printf("please input a,b,c:\n"); scanf("%d,%d,%d",&a,&b,&c); max = a; if(max<b) max = b; if(max<c) max = c; printf("The largest number is %d\n",max); return 0; }
4.有一个函数:x < 1, y = x; 1 <= x < 10 , 2x - 1; x >= 10 , 3x-11.
#include <stdio.h> int main() { double x,y; scanf("%lf",&x); if(x<1) y=x; else if(x>=10) y=3*x-11; else y=2*x-1; printf("最终的值为%lf\n",y); return 0; }
#include<stdio.h> int main() { double s=0,t=1; int n; for (n=1; n<=20; n++) { t = t*n; s = s + t; } printf("1!+2!+3!+....+20!=%0.16e\n",s); //%0.16e指的是以科学计数法的形式输出10的若干次方,非自然指数 return 0; }
6.请输出如下图案:
*
***
*****
*******
*****
***
*
#include <stdio.h> int main() { int i,j,k; for (i=0;i<=3;i++) { for (j=0;j<=2-i;j++) printf(" "); for (k=0;k<=2*i;k++) printf("*"); printf("\n"); } for (i=0;i<=2;i++) { for (j=0;j<=i;j++) printf(" "); for (k=0;k<=4-2*i;k++) printf("*"); printf("\n"); } return 0; }
7.输入有三个字符串,要求找出其中最大的字符串。
#include <stdio.h> #include <string.h> int main() { char str[3][20]; char string[20]; int i; for(i=0;i<3;i++) gets(str[i]); if(strcmp(str[0],str[1])>0) strcpy(string, str[0]); else strcpy(string, str[1]); if(strcmp(str[2],string)>0) strcpy(string, str[2]); printf("\n最大的字符串是:%s\n",string); return 0; }
8.用递归方法求n!
#include<stdio.h> int main() { int fac(int n); int n,y; printf("输入一个整数阶乘:"); scanf("%d",&n); y = fac(n); printf("%d!=%d\n",n,y); return 0; } int fac(int n) { int f; if(n<0) printf("n<0,数据错误"); else if(n == 0||n == 1) f = 1; else f = fac(n-1)*n; return(f); }