这是我的代码,对于我的 if 语句,我希望它位于两个值之间,例如:
if(rating < 5 > 2);
所以我是说我希望它只在该值低于 5 但高于 2 时打印命令。 有没有办法做到这一点?感谢您的宝贵时间。
这是我的代码。
public static void Main(string[] args)
{
Console.WriteLine("What would you rate starcraft out of 10?");
int rating = Console.Read();
if (rating < 5) ;
{
Console.WriteLine("Not good enough!");
Console.ReadLine();
}
if (rating > 5) ;
{
Console.WriteLine("OOOOOOOOO yeeeeeeee");
Console.ReadLine();
}
if (rating > 8) ;
{
Console.WriteLine("We are bestfriends now ;)");
Console.ReadLine();
最佳答案
使用conditional logical AND operator &&
:
if (rating < 5 && rating > 2)
{
}
或pattern matching ( read more #1 , read more #2 ):
if (rating is < 5 and > 2)
{
}
附言
您可以使用 switch
expression 进行一些重构并命令检查以删除一些代码重复并提高可读性(请注意,与以下相比,原始代码不涵盖 rating == 5
情况):
var rating = ...;
var message = rating switch
{
< 2 => "Terrible",
< 5 => "Not good enough!",
< 8 => "OOOOOOOOO yeeeeeeee",
_ => "We are bestfriends now ;)"
};
Console.WriteLine(message);
Console.ReadLine();
https://stackoverflow.com/questions/74889190/