您的位置:首页 > 编程语言 > C语言/C++

【C语言练习】3.0

2017-11-01 15:48 197 查看
1、 用标准C编程:找出整形数字1-100之间的素数,并打印出来。(素数:除了1和自己本身可以被整除。)

#include<stdio.h>
/*
用标准C编程:找出整形数字1-100之间的素数,并打印出来。
(素数:除了1和自己本身可以被整除。)
*/
main(){
int sum = 0;
for (int i = 1; i <= 100; i++){
for (int j = 2; j <= i; j++){
if (i%j == 0 && i != j){
break;
}
if (i%j == 0 && i == j){
sum++;
}
}
}
printf("100以内的素数数量为:%d", sum);
getch();
return 0;
}


2、 用标准C编程:有两个整形变量m、n,求出这两个数的最小公倍数。

#include<stdio.h>
/*
用标准C编程:有两个整形变量m、n,求出这两个数的最小公倍数。
*/
int getLeastCommonMultiple(int a, int b);
main(){
printf("请输入两个数");
int a = 0;
int b = 0;
scanf("%d %d",&a,&b);
int num=getLeastCommonMultiple(a,b);
printf("两个数字的最小公倍数为:%d",num);
getch();
return 0;
}
//辗转相除法求最大公约数
int greatestCommonDivisor(int a,int b){
int temp = 0;
if (a < b){
temp = a;
a = b;
b = temp;
}
while (b != 0){
temp = a%b;
a = b;
b = temp;
}
return a;
}
int getLeastCommonMultiple(int a,int b){
//将求最大公约数,最小公倍数写在一个函数中,极其容易操作相互影响,影响结果
//最好分为两个函数写,结构清晰
/*
int greatestCommonDivisor = 0;
int r = 0;
int a1 = a;
int b1 = b;
_Bool flag = 1;
while (flag){
if (r == 0){
greatestCommonDivisor = a1;
flag = 0;
}
else{
if (a1 > b1){
r = a1%b1;
}else {
r = b1%a1;
}
r = a1%b1;
a1 = b1;
b1 = r;
}
}
*/
return (a*b)/greatestCommonDivisor(a,b);//公式法求最大公倍数
}


用标准C编程:输出杨辉三角形的前10行:三角形的每一行是(x+y)^n的展开式各项的系数。

例如:

第一行是(x+y)^0,其系数为1;

第二行是(x+y)^1,其系数为1;

第三行是(x+y)^2,其展开式为x2+2xy+y2,系数分别为1,2,1;

直观形式如下:

1

1  1

1  2  1

1  3  3  1

1  4  6  4  1

1  5  10  10  5  1

#include<stdio.h>
/*
用标准C编程:输出杨辉三角形的前10行:三角形的每一行是(x+y)^n的展开式各项的系数。
直观形式如下:
1
1       1
1       2    1
1       3    3    1
1       4    6    4    1
1       5    10   10   5   1
*/
//先用递归求出第n行第m项的数
int method(int n,int m){
if (n == m || m == 1){
return 1;
}
return method(n - 1, m) + method(n - 1, m - 1);
}

main(){
//用for循环打印出每行
for (int i = 1; i <= 10; i++){
for (int j = 1; j <= i; j++){
int z = method(i, j);
printf("%d \t ",z);
}
printf("\n");
}
getch();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c语言