无法理解代码段

Zan*_*ane -4 c#

我正在做一些基本的C#练习来学习C#.网站也提供了问题的解决方案,但我无法理解代码.

问题:编写一个C#程序来检查整数是否在100或200之间.

示例输出: 输入一个25 False的整数

方案:

public class Exercise22
{
    static void Main(string[] args)
    {
        Console.WriteLine("\nInput an integer:");
        int x = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine(result(x));
    }
    public static bool result(int n) 
    { 
        //Can't understand the code below - 
        //why is the "<=10" and "return false" used 

        if (Math.Abs(n - 100) <= 10 || Math.Abs(n - 200) <= 10)
            return true;
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)

Ren*_*ogt 5

Math.Abs() 给出参数的绝对值.

如果n介于90和110之间(20左右,大约100),则n-100介于-10和之间10,因此Math.Abs()将在0和之间返回一个值10.

200也是如此.

但是,您可以将其简化为:

return Math.Abs(n-100) <= 10 || Math.Abs(n-200) <= 10;
Run Code Online (Sandbox Code Playgroud)

因此,如果n在其中一个范围内,true则返回并且函数结束.

否则,该功能会跳过return true并继续return false.