输入1-12中的数字判断此月有多少天并在控制台上输出 switch case
时间: 2024-02-20 20:56:06 浏览: 24
好的,以下是实现代码:
```python
month = int(input("请输入1-12中的一个数字,表示要查询的月份:"))
days = 0 # 记录天数
# 判断月份并计算天数
switcher = {
1: 31,
2: 28,
3: 31,
4: 30,
5: 31,
6: 30,
7: 31,
8: 31,
9: 30,
10: 31,
11: 30,
12: 31
}
days = switcher.get(month, "输入的月份不合法!")
if days == "输入的月份不合法!":
print(days)
else:
print("{}月有{}天。".format(month, days))
```
运行结果如下:
```
请输入1-12中的一个数字,表示要查询的月份:2
2月有28天。
```
相关问题
输入1-12月份 判断出此月份有多少天并在控制台上输出(swtich case)
好的,我可以帮你写一个用 switch case 实现的程序来判断每个月份有多少天。代码如下:
```csharp
Console.WriteLine("请输入月份(1-12):");
int month = int.Parse(Console.ReadLine());
int days = 0;
switch (month)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
days = 31;
break;
case 4:
case 6:
case 9:
case 11:
days = 30;
break;
case 2:
Console.WriteLine("请输入年份:");
int year = int.Parse(Console.ReadLine());
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
{
days = 29;
}
else
{
days = 28;
}
break;
default:
Console.WriteLine("输入的月份不正确!");
break;
}
if (days > 0)
{
Console.WriteLine($"{month}月有{days}天。");
}
```
以上代码可以根据输入的月份和年份(2月份需要判断是否为闰年)来判断该月有多少天,并在控制台上输出。注意,这里的输入都是通过控制台读取的,你可以根据需要进行修改。
js输入1-12月份 判断出此月份有多少天并在控制台上输出(swtich case)
好的,以下是实现这个功能的代码:
```js
let month = prompt("请输入月份(1-12):");
let days;
switch (month) {
case "1":
case "3":
case "5":
case "7":
case "8":
case "10":
case "12":
days = 31;
break;
case "4":
case "6":
case "9":
case "11":
days = 30;
break;
case "2":
let year = prompt("请输入年份:");
days = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0) ? 29 : 28;
break;
default:
console.log("请输入正确的月份!");
break;
}
if (days) {
console.log(`${month}月有${days}天。`);
}
```
这段代码首先通过 `prompt` 函数获取用户输入的月份,然后根据不同的月份使用 `switch case` 结构计算出该月份有多少天,并将结果存储在 `days` 变量中。
对于大部分月份,天数是固定的,可以直接通过 `case` 语句指定。对于 2 月份,需要根据闰年和平年来计算天数。最后,如果 `days` 变量有值,就输出结果到控制台。