练习1 阶乘与阶乘求和
程序实现以下几点
1. 计算 n的阶乘。
2. 计算 f(n) = 1!+2!+3!+……+n!
3. 输入-1退出程序
#include <stdio.h>
// #include <conio.h> //需要使用到getch()函数
// 程序实现以下几点
// 1. 计算 n的阶乘。
// 2. 计算 f(n) = 1!+2!+3!+……+n!
// 3. 输入-1退出程序
int factorial(int n) // 计算n的阶乘函数
{
int fac = 1;
for (int i = 1; i <= n; i++)
{
fac *= i;
}
return fac;
}
int sum_factorial(int n) // f(n) = 1!+2!+3!+……+n!
{
int sum = 0;
for (int i = 1; i <= n; i++)
{
sum += factorial(i);
}
return sum;
}
int main()
{
printf("输入-1退出程序\n");
while (1)
{
int n = 0;
scanf("%d", &n);
if(n == -1)
{
printf("退出程序!!!");
break;
}
int result_fact = factorial(n); // 计算阶乘
int result_sum = sum_factorial(n); // 计算阶乘求和
printf("%d! = %d\n", n, result_fact); // 打印阶乘结果
printf("f(%d) = %d\n", n, result_sum); // 打印阶乘求和结果
}
return 0;
}
// 注由于阶乘数字过大会导致int取值溢出,本程序求和至12,阶乘至17,想计算更大的阶乘可以使用long long
练习2 打印整形每一位
接受一个整型值(无符号),按照从高到底与从低到高的顺序打印它的每一位。
例如:输入:1234,
输出 1 2 3 4
4 3 2 1
// 接受一个整型值(无符号),按照从高到底与从低到高的顺序打印它的每一位。
// 例如:输入:1234,
// 输出 1 2 3 4
// 4 3 2 1
#include <stdio.h>
#include <math.h>
typedef unsigned int uint;
uint num = 0;
uint num_low = 0;
// 定义一个求无符号整形有几位的函数
int count(uint x)
{
int count = 0;
if (x == 0)
{
count = 1; // 特判0的情况
}
else
{
while (x != 0)
{
x /= 10;
count++;
}
}
return count;
}
// 按高位取出每个数字并间隔打印
void high_take(uint x)
{
int n = 0;
int nu = 0;
n = count(x);
int m = (int)pow((double)10,(double)n-1); //调用指数函数
nu = x / m;
num = x % m;
printf("%d ",nu);
}
// 按低位取出每个数字并间隔打印
void low_take(uint x)
{
int nu = 0;
nu = x % 10;
num_low = x / 10;
printf("%d ",nu);
}
int main()
{
printf("请输入一个无符号整形\n");
scanf("%d",&num);
num_low = num;
while (num != 0)
{
high_take(num); //从高到低打印
}
printf("\n");
while (num_low != 0)
{
low_take(num_low); //从低到高打印
}
return 0;
}
练习3 冒泡排序
#include <stdio.h>
// 冒泡排序
int arr[] = {2, 4, 3, 8, 6, 7, 9, 0};
// 数组传参传的是数组的首地址
// 两种写法 1:数组 2:指针
void bubblesort_decrease(int arr[], int x) // 降序冒泡排序函数
{
for (int j = 0; j < x - 1; j++)
{
for (int i = 0; i < x - j - 1; i++)
{
if (arr[i] < arr[i + 1])
{
int s = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = s;
}
}
}
}
void bubblesort_increase(int arr[], int x) // 升序冒泡排序函数
{
for (int j = 0; j < x - 1; j++)
{
for (int i = 0; i < x - j - 1; i++)
{
if (arr[i] > arr[i + 1])
{
int s = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = s;
}
}
}
}
int main()
{
int n = sizeof(arr) / 4; // 计算数组的占用字节
// printf("%d",n);//得到数组中有几个数据
// 降序打印
bubblesort_decrease(arr, n);
for (int i = 0; i < n; i++)
{
printf("%d ", arr[i]);
}
// 升序打印
bubblesort_increase(arr, n);
printf("\n");
for (int i = 0; i < n; i++)
{
printf("%d ", arr[i]);
}
return 0;
}