初学c#麻烦

use*_*117 -1 c#

我是c#的新手,我有一点问题.我想制作一个简单的程序来询问用户1-50之间的整数,然后在控制台上显示是否为奇数.所以,我试过的是这样的:

 Console.WriteLine("Skriv ut ett heltal: ");
 int x = int.Parse(Console.ReadLine());

 if (x == 1,3,5,7,9,11,13,15,17,19)
 {
     Console.WriteLine("The number is odd");
 }
 else 
 {
     Console.WriteLine("The number is not odd");
 }
Run Code Online (Sandbox Code Playgroud)

现在我在if语句中遇到错误.我怎样才能解决这个问题?

Mic*_*ray 10

C#不允许您指定多个值来使用单个if语句检查变量.如果你想这样做,你需要单独检查每个值(1,3,5等),这将是很多冗余类型.

在这个特定的例子中,检查某些东西是奇数还是偶数的更简单方法是使用模数运算符检查除以2之后的余数%:

if (x % 2 == 1)
{
   Console.WriteLine("The number is odd");
}
else 
{
    Console.WriteLine("The number is even");
}
Run Code Online (Sandbox Code Playgroud)

但是,如果您确实需要检查列表,那么简单的方法是Contains在数组上使用该方法(ICollection<T>实际上).为了使它变得简单易用,您甚至可以编写一个扩展函数,让您以语法上的方式检查列表:

public static class ExtensionFunctions
{
    public static bool In<T>(this T v, params T[] vals)
    {
        return vals.Contains(v);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后你可以说:

if (x.In(1,3,5,7,9,11,13,15,17,19)) 
{
    Console.WriteLine("The number is definitely odd and in range 1..19");
}
else 
{
    Console.WriteLine("The number is even, or is not in the range 1..19");
}
Run Code Online (Sandbox Code Playgroud)

瞧!:)

  • 如果`x%2 == 0`不是吗? (2认同)