簡體   English   中英

C# 對兩位整數的加法

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM