[英]C# Addition on a double digit integer
更具体地说,我想知道如何制作它以便我可以接受来自用户的两位数输入并对两位数执行加法。 示例:用户输入 = 42;
4+2 = 6。我找不到这个动作的名称,所以我在这里找不到这样的答案。 我应该补充一点,我宁愿避免创建更多的整数
这是您可以使用的方法。 只需使用两个字符的输入string
作为参数。 由于输入string
无效或两个数字的总和,您将收到异常。
public int AddTwoDigitString(string input)
{
if(input == null)
throw new ArgumentNullException(nameof(input));
if(input.Length != 2)
throw new ArgumentException($"`{nameof(input)}` must be two characters long");
int firstDigit, secondDigit;
if(int.TryParse(input[0].ToString(), out firstDigit) == false)
throw new ArgumentException("First character is not an integer.");
if(int.TryParse(input[1].ToString(), out secondDigit) == false)
throw new ArgumentException("Second character is not an integer.");
return firstDigit + secondDigit;
}
您可以通过计算自己完成:
int b= Int32.Parse(userinput);
int a =b%10+b/10;
如果 b 是 42,那么 a 将是 2+4=6
如果你不知道你有多少位数:
int b= Int32.Parse(userinput);
int a=0;
while(b!=0)
{
a+=(b%10);
b=b/10;
}
您可以尝试使用System.Linq
Aggregate
函数, System.Linq
所示
return userInput.ToCharArray()
.Aggregate(0, (result, character) => result += int.Parse(character.ToString()));
其中 lamda 表达式是将为输入中的每个字符执行的累加器函数。
你可以试试这个:
整数;
{
Console.Write("Insert the number");
number = Convert.ToInt32(Console.ReadLine());
Console.Write("Equals" + Addition(number).ToString());
Console.ReadKey();
}
// Operation that returns the addition of the digits of a number
static int Addition(int number){
int acum = 0;
while (num != 0){
var digit = number % 10;
acum += digit;
number = number / 10;
}
return acum;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.