22、输入月份输出天数,输入一个数字n(1~12),其中2月为28天 23、输出n的阶乘 输入一个数n 输出n的阶乘C语言
时间: 2024-10-20 07:17:36 浏览: 22
在C语言中,你可以分别编写两个函数来解决这两个问题:
1. **输入月份输出天数**:
```c
#include <stdio.h>
int days_in_month(int month) {
switch(month) {
case 1: // January
case 3: // March
case 5: // May
case 7: // July
case 8: // August
case 10: // October
case 12: // December
return 31;
case 4: // April
case 6: // June
case 9: // September
case 11: // November
return 30;
case 2: // February (accounting for leap year)
default:
if ((month == 2 && calendar_is_leap_year()) || month != 2) {
return 28; // Standard years have 28 days in February
} else {
return 29; // Leap years have 29 days in February
}
}
}
// Function to check if a year is a leap year (using the common rule)
int calendar_is_leap_year() {
int year;
scanf("%d", &year);
if (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) {
return 1;
}
return 0;
}
int main() {
int n;
printf("Enter a month between 1 and 12: ");
scanf("%d", &n);
printf("Days in %dth month: %d\n", n, days_in_month(n));
return 0;
}
```
这个程序首先询问用户输入月份,然后根据给定的月份返回相应的天数,会考虑闰年的情况。
2. **输出n的阶乘**:
```c
#include <stdio.h>
long long factorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
int main() {
int n;
printf("Enter a number: ");
scanf("%d", &n);
printf("The factorial of %d is: %lld\n", n, factorial(n));
return 0;
}
```
这个函数递归地计算给定数字的阶乘,并将结果作为长整型返回,因为较大的阶乘值可能会超出普通整数范围。
阅读全文