C#控制台用户输入一个时间计算机输出上午好
时间: 2023-08-06 22:09:03 浏览: 52
好的,那么可以使用以下代码实现:
```csharp
using System;
class Program {
static void Main(string[] args) {
Console.Write("请输入时间(格式为hh:mm:ss):");
string timeStr = Console.ReadLine();
DateTime time = DateTime.Parse(timeStr);
if (time.Hour < 12) {
Console.WriteLine("上午好!");
}
else {
Console.WriteLine("下午好!");
}
}
}
```
这段代码会先提示用户输入时间,然后将用户输入的字符串转换为 DateTime 对象,并根据时间的小时数判断是上午还是下午,最后输出对应的问候语。注意,这段代码假设用户输入的时间是符合格式要求的,如果用户输入了无效的字符串,就会抛出异常。
相关问题
c#控制台输入时间去掉冒号输出
可以使用 `DateTime.ParseExact()` 方法将带冒号的时间字符串转化为 `DateTime` 类型,并使用 `ToString()` 方法将其格式化为不带冒号的字符串。以下是示例代码:
```csharp
using System;
namespace RemoveColon
{
class Program
{
static void Main(string[] args)
{
Console.Write("请输入时间(格式为hh:mm:ss):");
string timeStr = Console.ReadLine();
DateTime time = DateTime.ParseExact(timeStr, "HH:mm:ss", null);
string timeWithoutColon = time.ToString("HHmmss");
Console.WriteLine(timeWithoutColon);
Console.ReadKey();
}
}
}
```
在上面的代码中,`DateTime.ParseExact()` 方法的第二个参数是时间字符串的格式,其中 `HH` 表示小时数,`mm` 表示分钟数,`ss` 表示秒数。然后,使用 `ToString()` 方法将 `DateTime` 类型格式化为不带冒号的字符串,其中 `HH` 表示小时数,`mm` 表示分钟数,`ss` 表示秒数。
c#用控制台设计一个输入名字和时间输出名字+上午好/下午好/晚上好的代码
可以使用以下代码实现:
```csharp
using System;
namespace Greeting
{
class Program
{
static void Main(string[] args)
{
Console.Write("请输入您的名字:");
string name = Console.ReadLine();
DateTime now = DateTime.Now;
string greeting = "";
if (now.Hour >= 6 && now.Hour < 12)
{
greeting = "上午好";
}
else if (now.Hour >= 12 && now.Hour < 18)
{
greeting = "下午好";
}
else
{
greeting = "晚上好";
}
Console.WriteLine($"{name}{greeting}!");
Console.ReadKey();
}
}
}
```
运行程序后,会提示用户输入名字,然后根据当前时间输出对应的问候语。注意,这里使用了 `DateTime.Now` 获取当前时间,并根据时间的小时数来判断是上午、下午还是晚上。