[英]C# Addition on a double digit integer
To be more specific, I would like to know how to make it so that i can accept a two digit input from a user and perform addition on the two digits.更具体地说,我想知道如何制作它以便我可以接受来自用户的两位数输入并对两位数执行加法。 Example: userInput = 42;示例:用户输入 = 42;
4+2 = 6. I could not find out the name of this action so i could not find such an answer on here. 4+2 = 6。我找不到这个动作的名称,所以我在这里找不到这样的答案。 I should add that i would rather avoid creating more integers我应该补充一点,我宁愿避免创建更多的整数
Here is a method you can use.这是您可以使用的方法。 Just use a two character input string
as a parameter.只需使用两个字符的输入string
作为参数。 You'll either get an exception because the input string
is invalid or the sum of both digits.由于输入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;
}
You can do it by yourself by calculating:您可以通过计算自己完成:
int b= Int32.Parse(userinput);
int a =b%10+b/10;
and than if b its 42, so a will be 2+4=6如果 b 是 42,那么 a 将是 2+4=6
if you don't know how many digits you have:如果你不知道你有多少位数:
int b= Int32.Parse(userinput);
int a=0;
while(b!=0)
{
a+=(b%10);
b=b/10;
}
You can try and use Aggregate
function from System.Linq
like this您可以尝试使用System.Linq
Aggregate
函数, System.Linq
所示
return userInput.ToCharArray()
.Aggregate(0, (result, character) => result += int.Parse(character.ToString()));
where the lamda expresion is the accumulator function that will be executed for each character in the input.其中 lamda 表达式是将为输入中的每个字符执行的累加器函数。
You could try this:你可以试试这个:
int number;整数;
{
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.