C语言程序学习例题

一、编程题

1.1 输入三个整数,按从小到大的顺序排列输出

冒泡法

#include <stdio.h>
int main() {
int a[3];
printf("请输入三个正整数:\n");
for (int i = 0; i < 3; i++) {
scanf("%d", &a[i]);
}
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3 - i - 1; j++) {
if (a[j] > a[j + 1]) {
int temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
printf("从小到大排列为:%d %d %d\n", a[0], a[1], a[2]);
return 0;
}

比较法

#include <stdio.h>
int main() {
int a, b, c;
printf("请输入三个正整数: ");
scanf("%d %d %d", &a, &b, &c);
// 使用条件运算符简化排序逻辑
if (a > b) {
int temp = a; a = b; b = temp; // 确保 a <= b
}
if (b > c) {
int temp = b; b = c; c = temp; // 确保 b <= c
}
if (a > b) {
int temp = a; a = b; b = temp; // 再次确保 a <= b
}
printf("从小到大排列为:%d %d %d\n", a, b, c);
return 0;
}

1.2阶乘和

#include <stdio.h>
int main() {
int number, f = 1, sum = 0;
printf("请输入一个正整数来计算其阶乘和: ");
scanf("%d", &number);
for (int i = 1; i <= n; i++) {
f *= i; // 计算当前数字的阶乘
sum += f; // 将当前阶乘加到总和中
}
printf("从1到%d的阶乘和为:%d\n", number, sum);
return 0;
}

递归法

#include <stdio.h>
// 递归函数用于计算阶乘
long long factorial(int n) {
if (n == 0 || n == 1)
return 1;
else
return n * factorial(n - 1);
}

int main() {
int number, i;
long long sum = 0;


printf("请输入一个正整数来计算其阶乘和: ");
scanf("%d", &number);

for (i = 1; i <= number; i++) {
// 计算当前数字的阶乘并累加到总和中
sum += factorial(i);
}

printf("从1到%d的阶乘和为:%lld\n", number, sum);

return 0;

}

1.3 数字金字塔

#include <stdio.h>

// 数字金字塔
int main() {
int i, j, n, y;
// 提示用户输入金字塔的层数
printf("输入金字塔的层数\n");

// 读取用户输入的层数并存储在变量n中
scanf("%d", &n);
// 外层循环控制金字塔的行数,从1到n
for (i = 1; i <= n; i++) {
// 第一个内层循环用于打印每行前面的空格
// 空格的数量随着行数增加而减少
for (j = 1; j <= n - i ; j++)
printf(" ");

// 第二个内层循环用于打印数字
// 每一行中的数字等于当前行号(即i)
for (y = 1; y <= i; y++)
printf("%d ", i);

// 在每一行的末尾换行,以便开始新的一行
printf("\n");
}
return 0;

}

1.4 判断一个正整数是否为3和5的倍数

#include <stdio.h>

//判断一个正整数是否为3和5的倍数

int main() {
int a;
printf("输入一个正整数");
scanf("%d",&a);
if(a%3==0&&a%5==0)
printf("yes");
else
printf("no");

return 0;
}

1.5 搬砖问题。36块砖,36人搬,男搬4,女搬3,两个小孩抬一块砖,要求一次搬完,问男人、女人和小孩各需多

#include <stdio.h>
//搬砖问题。36块砖,36人搬,男搬4,女搬3,两个小孩抬一块砖,要求一次搬完,问男人、女人和小孩各需多
int main()
{
int x, y, z;


for (x = 0; x <= 9; x++) //4
{
for (y = 0; y <= 12; y++) //4
{
for (z = 0; z <= 72; z = z + 2) //4
{
if (x + y + z == 36 && 4 * x + 3 * y + z / 2 == 36)//4
{
printf("men=%d,women=%d,children=%d\n", x, y, z); //1 //2
}
}
}

}

return 0;

}

1.6 回文数

#include <stdio.h>

int main() {
int x, a, b, c, d, e;

printf("输入一个五位数: ");
scanf("%d", &x);

// 确保输入的是五位数
if (x >= 10000 && x <= 99999) {
a = x / 10000; // 获取万位上的数字
b = (x / 1000) % 10; // 获取千位上的数字
c = (x / 100) % 10; // 获取百位上的数字
d = (x / 10) % 10; // 获取十位上的数字
e = x % 10; // 获取个位上的数字

// 判断是否为回文数
if (a == e && b == d) {
printf("是回文数\n");
} else {
printf("不是回文数\n");
}
} else {
printf("请输入有效的五位数。\n");
}

return 0;
}