简体   繁体   中英

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;

4+2 = 6. I could not find out the name of this action so i could not find such an answer on here. 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. You'll either get an exception because the input string is invalid or the sum of both digits.

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

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

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.

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;

        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM