C# 检查数字是否可以被 24 整除

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19395334/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 14:54:06  来源:igfitidea点击:

Check if number is divisible by 24

c#if-statement

提问by Hoyo

I'd like to put up a if function, that will see if the variable is dividable by 24, if it's then it does the function else not, same logic however, I want to see if the output is a perfect number, e.g if we do 24/24 that will get 1, that's a perfect number. If we do 25/24 then it'll get 1.041 which is not a perfect number, the next perfect number will come when it reaches 48 that will be 48/24 which will get 2 that's a perfect number.

我想建立一个 if 函数,它将查看变量是否可被 24 整除,如果是,则它执行该函数,否则不会执行该函数,但是,相同的逻辑,我想查看输出是否为完美数,例如,如果我们做 24/24 会得到 1,这是一个完美的数字。如果我们做 25/24 那么它会得到 1.041,这不是一个完美的数字,下一个完美的数字会在它达到 48 时出现,这将是 48/24,它将得到 2,这是一个完美的数字。

采纳答案by Hanlet Esca?o

Use the Modulusoperator:

使用模数运算符:

if (number % 24 == 0)
{
   ...
}

The % operator computes the remainder after dividing its first operand by its second. All numeric types have predefined remainder operators.

% 运算符计算第一个操作数除以第二个操作数后的余数。所有数字类型都有预定义的余数运算符。

Pretty much it returns the remainder of a division: 25 % 4 = 1 because 25 fits in 24 once, and you have 1 left. When the number fits perfectly you will get a 0 returned, and in your example that is how you know if a number is divisible by 24, otherwise the returned value will be greater than 0.

几乎它返回除法的余数:25 % 4 = 1 因为 25 一次可以放入 24,而您还剩下 1。当数字完美匹配时,您将返回 0,在您的示例中,这就是您如何知道一个数字是否可以被 24 整除,否则返回的值将大于 0。

回答by Nikhil Agrawal

How about using Modulusoperator

如何使用运算符

if (mynumber % 24 == 0)
{
     //mynumber is a Perfect Number
}
else
{
    //mynumber is not a Perfect Number
}

What it does

它能做什么

Unlike /which gives quotient, the Modulus operator (%) gets the remainder of the division done on operands. Remainder is zero for perfect number and remainder is greater than zero for non perfect number.

/给出商不同,模运算符 ( %) 获得对操作数完成的除法的余数。完全数的余数为零,非完全数的余数大于零。