C语言输入一个月份,输出对应的英文名称,要求用指针数 12个月的英文名称。试编写相应程序。
时间: 2024-02-27 11:53:11 浏览: 26
好的,以下是代码实现:
```c
#include <stdio.h>
void monthName(int month, char *name) {
char *months[] = {"January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"};
// 将对应月份的英文名称拷贝到name指向的字符串中
strcpy(name, months[month - 1]);
}
int main() {
int month;
char name[20];
printf("请输入月份:");
scanf("%d", &month);
monthName(month, name);
printf("%d月对应的英文名称是:%s\n", month, name);
return 0;
}
```
程序中,我们定义了一个`monthName`函数,用来获取对应月份的英文名称。在函数中,我们定义了一个字符串数组`months`,其中存储了12个月份的英文名称。我们将对应月份的英文名称拷贝到`name`指向的字符串中,最后在`main`函数中输出即可。需要注意的是,由于`name`指向的字符串可能会被修改,因此我们需要将其声明为字符数组,而不是字符指针。
相关问题
c语言中输入一个月份,输出对应的英文名称,要求用指针数组表示12个月的英文名称,试试编写相应程序代码
好的,这个问题可以用一个指针数组来表示 12 个月的英文名称,然后根据用户输入的月份,输出对应的英文名称。
下面是 C 代码实现:
```c
#include <stdio.h>
#include <string.h>
int main() {
char *months[] = {"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"};
int month;
printf("Enter month number (1-12): ");
scanf("%d", &month);
if (month < 1 || month > 12) {
printf("Invalid month number\n");
return 0;
}
printf("Month name: %s\n", months[month - 1]);
return 0;
}
```
这个程序首先定义了一个指针数组 months,用于表示 12 个月的英文名称。然后,程序提示用户输入一个月份,如果输入的月份不在 1-12 范围内,则输出错误信息;否则,程序输出对应的英文名称。
例如,如果用户输入 3,那么程序输出 "Month name: March"。
用c语言编写程序,输入一个月份,输出对应的英文名称,要求用指针数组表示12个月的英文名称
好的,这个问题我可以回答。以下是C语言代码:
```c
#include <stdio.h>
#include <string.h>
int main() {
char *months[] = {"January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"};
int month_num;
printf("Enter a month number (1-12): ");
scanf("%d", &month_num);
if (month_num < 1 || month_num > 12) {
printf("Invalid month number!\n");
return 1;
}
char *month_name = months[month_num - 1];
printf("The month name is: %s\n", month_name);
return 0;
}
```
这个程序中,我们使用了一个指针数组 `months` 来存储 12 个字符串,每个字符串表示一个月的英文名称。然后,我们通过 `scanf` 函数获取用户输入的月份,检查其合法性,然后使用指针数组来获取对应的月份名称,最后输出到屏幕上。
希望这个程序能够帮到你!
相关推荐
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)