我将如何在C#中为以下内容创建一个方法。
如果是奇数,则应返回整数/2。如果是偶数,则应返回自身相乘的整数。如果该整数为null,则应返回12345。
任何帮助都将不胜感激谢谢
你是如何获得输入的?对于本例,我假设它是一个字符串,因为默认情况下int
不能为null。但是,您可以使用int?
创建一个可为空的int
private int MethodName(string input)
{
//Validate the input is an int. You may want to support decimals here.
//decimal.TryParse is the method. As dividing an odd number by 2 using an int will round.
var validInput = Int32.TryParse(input, out var result);
//You may want to return this if the input is 0 as well.
if (!validInput)
return 12345;
//An even number will have remainder of 0 when divied by 2...
var isEven = result % 2 == 0;
if (isEven)
return result * result;
//Otherwise it must be odd
return result / 2;
}