c语言函数基础练习十题
时间: 2024-01-28 17:12:11 浏览: 91
以下是10道C语言函数基础练习题的答案:
1. 交换两个变量的值
```c
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
```
2. 计算一个数的平方
```c
int square(int num) {
return num * num;
}
```
3. 判断一个数是否为素数
```c
int isPrime(int num) {
int i;
for (i = 2; i <= num / 2; i++) {
if (num % i == 0) {
return 0;
}
}
return 1;
}
```
4. 计算一个数的阶乘
```c
int factorial(int num) {
int i, result = 1;
for (i = 1; i <= num; i++) {
result *= i;
}
return result;
}
```
5. 计算两个数的最大公约数
```c
int gcd(int a, int b) {
int temp;
while (b != 0) {
temp = b;
b = a % b;
a = temp;
}
return a;
}
```
6. 计算两个数的最小公倍数
```c
int lcm(int a, int b) {
int temp = gcd(a, b);
return a * b / temp;
}
```
7. 判断一个数是否为回文数
```c
int isPalindrome(int num) {
int temp = num, reverse = 0;
while (temp != 0) {
reverse = reverse * 10 + temp % 10;
temp /= 10;
}
return num == reverse;
}
```
8. 判断一个数是否为 Armstrong 数
```c
int isArmstrong(int num) {
int temp = num, digits = 0, sum = 0;
while (temp != 0) {
digits++;
temp /= 10;
}
temp = num;
while (temp != 0) {
sum += pow(temp % 10, digits);
temp /= 10;
}
return num == sum;
}
```
9. 将一个十进制数转换为二进制数
```c
void decimalToBinary(int num) {
int binary[32], i = 0;
while (num > 0) {
binary[i] = num % 2;
num /= 2;
i++;
}
for (int j = i - 1; j >= 0; j--) {
printf("%d", binary[j]); }
}
```
10. 计算三角形的面积
```c
double triangleArea(double a, double b, double c) {
double s = (a + b + c) / 2;
double area = sqrt(s * (s - a) * (s - b) * (s - c));
return area;
}
```
阅读全文