-1

我是 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");
 }

现在我的 if 语句条件出现错误。我怎样才能解决这个问题?

4

9 回答 9

11

C# 不允许您使用单个if语句指定多个值来检查变量。如果您想这样做,则需要单独检查每个值(1、3、5 等),这将是很多多余的输入。

在此特定示例中,检查某事物是奇数还是偶数的更简单方法是使用模运算符检查除以 2 后的余数%

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

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

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

然后你可以说:

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");
}

瞧!:)

于 2013-07-09T01:04:53.643 回答
4
if(x % 2 == 0)
{
// It's even
}
else
{
// It's odd
}
于 2013-07-09T01:04:46.620 回答
4

如果要测试 x 是否是特定列表中的数字:

int[] list = new int[]{ 1,3,5,7,9,11,13,15,17,19};
if(list.Contains(x)) 

检查整数是否为奇数的常用方法是检查它是否被 2 整除:

if(x % 2 == 1)
于 2013-07-09T01:05:57.940 回答
1

x == 1,3,5,7,9,11,13,15,17,19不是表达多个选项的有效语法。如果您真的想这样做,那么您可以使用以下switch语句:

 switch(x) {
     case 1:
     case 3:
     case 5:
     case 7:
     case 9:
     case 11:
     case 13:
     case 15:
     case 17:
     case 19:
          // is odd
          break;
     default:
          // is even
          break;
 }

正确的方法是使用模运算符%来确定一个数字是否可以被 2 整除,而不是尝试每个奇数,如下所示:

if( x % 2 == 0 ) {
   // even number
}  else {
   // odd number
}
于 2013-07-09T01:05:06.850 回答
1

这不是有效的 C#。你不能像那样测试集合包含。无论如何,测试世界上所有的数字是不切实际的。

你为什么不这样做呢?

if (x &1 == 1) // mask the 1 bit

按位运算非常快,因此代码应该非常快。

于 2013-07-09T01:05:52.500 回答
1

虽然正如其他人所指出的那样,这不是解决此问题的最佳方法,但在这种情况下出现错误的原因是因为在 if 语句中不能有多个值。你必须这样说:

if (x == 1 || x == 3 || x == 5)

如果你不知道,||是“或”的符号

于 2013-07-09T01:07:08.523 回答
1

如果您有多个条件,您的 if 语句应该是这样的:

如果任何一个条件为真:

if(x == 1 || x == 3 || x == 5) 
{
    //it is true
}

如果所有条件都必须为真:

if(x == 1 && y == 3 && z == 5) 
{
    //it is true
}

但是,如果您只是在寻找奇数/偶数。%如另一个答案所说,使用运算符。

于 2013-07-09T01:09:56.810 回答
0

尝试以下操作:

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

Console.WriteLine(x % 2 == 1 ? "The number is odd" : "The number is not odd");

x % 2 == 1 对输入进行模数 2(在数字介于 0 和 2 之间之前,尽可能多地取掉 '2 - 所以在这种情况下为 0 或 1)

于 2013-07-09T01:05:23.100 回答
0

一种方法是:

if (x == 1 || 3 || 5){ 
Console.writeLine("oddetall");
}

或者因此可以创建一个 Array []

int[] odd = new int[3]; // how many odd to be tested
if(x=odd){
Console.WriteLine("Oddetall");
}
于 2015-04-11T21:16:09.360 回答