[英]Beginner c# trouble
我是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语句条件出现错误。 我怎样才能解决这个问题?
C#不允许您指定多个值以使用单个if
语句来检查变量。 如果您想以这种方式进行操作,则需要分别检查每个值(1、3、5等),这将是很多多余的输入。
在此特定示例中,检查模数是否为奇数或偶数的更简单方法是使用模运算符%
来检查除以2后的余数:
if (x % 2 == 1)
{
Console.WriteLine("The number is odd");
}
else
{
Console.WriteLine("The number is even");
}
但是,如果确实需要检查列表,那么简单的方法是在数组(实际上是ICollection<T>
)上使用Contains
方法。 为了使它变得简单易用,您甚至可以编写扩展功能,使您可以以语法上漂亮的方式检查列表:
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");
}
瞧! :)
if(x % 2 == 0)
{
// It's even
}
else
{
// It's odd
}
如果要测试x是否为特定列表中的数字:
int[] list = new int[]{ 1,3,5,7,9,11,13,15,17,19};
if(list.Contains(x))
检查整数是否为奇数的常见方法是检查整数是否除以2:
if(x % 2 == 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
}
那不是有效的C#。 您不能像这样测试集合包含。 无论如何,测试世界上所有的数字都是不切实际的。
您为什么不这样做呢?
if (x &1 == 1) // mask the 1 bit
按位运算非常快,因此代码也应该很快。
正如其他人指出的那样,这不是解决此问题的最佳方法,但在这种情况下出现错误的原因是因为在if语句中不能有多个值。 您必须这样说:
if (x == 1 || x == 3 || x == 5)
如果您不知道, ||
是“或”的符号
如果您有多个条件,则if语句应类似于以下内容:
如果任一条件为真:
if(x == 1 || x == 3 || x == 5)
{
//it is true
}
如果所有条件都必须为真:
if(x == 1 && y == 3 && z == 5)
{
//it is true
}
但是,如果您只想查找奇/偶数。 使用%
运算符作为其他答案。
请尝试以下操作:
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)
一种方法是:
if (x == 1 || 3 || 5){
Console.writeLine("oddetall");
}
或因此可以创建一个数组[]
int[] odd = new int[3]; // how many odd to be tested
if(x=odd){
Console.WriteLine("Oddetall");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.