问题
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.
回答1:
Use the Modulus operator:
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.
回答2:
How about using Modulus operator
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.
来源:https://stackoverflow.com/questions/19395334/check-if-number-is-divisible-by-24