如何进行减法?
确定停止条件 - 您希望您的 while 循环继续进行,直到数字 a、b 和进位都变为零。换句话说,条件应该是 || 乙 || 携带
将下一位数字添加到总和中 - 由于结果编码为十进制,因此您需要将数字 d 乘以下一个连续的十的幂。一种简单的方法是添加一个新变量 m,它从 1 开始,每次迭代乘以 10。
有人可以帮忙做减法吗:
static int addition(int num1, int num2)
{
int sum = 0, digit = 0, carry = 0, digit_rank = 1;
// Calculate the sum
while (num1 > 0 || num2 > 0 || carry > 0)
{
// Calculate the digit
digit = num1 % 10 + num2 % 10 + carry;
// Determine if you should carry or not
if (digit > 7)
{
carry = 1;
digit %= 8;
}
else
carry = 0;
// Add the digit at the beggining of the sum
sum += digit * digit_rank;
digit_rank *= 10;
// Get rid of the digits of a and b we used
num1 /= 10;
num2 /= 10;
}
return sum;
}