初学c#麻烦

时间:2013-07-09 01:01:51

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

现在我在if语句中遇到错误。我该如何解决这个问题?

9 个答案:

答案 0 :(得分:10)

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

瞧! :)

答案 1 :(得分:4)

if(x % 2 == 0)
{
// It's even
}
else
{
// It's odd
}

答案 2 :(得分: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)

答案 3 :(得分: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
}

答案 4 :(得分:1)

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

为什么不这样做呢?

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

按位操作非常快,因此代码应该非常快。

答案 5 :(得分:1)

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

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

如果您不知道,||是'或'的符号

答案 6 :(得分:1)

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

如果有任何一个条件成立:

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

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

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

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

答案 7 :(得分: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(尽可能多地关闭&#39; 2&#39; s,直到数字介于0和2之间 - 在这种情况下为0或1)

答案 8 :(得分: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");
}
相关问题