直接将两个八进制数相减而不转换为十进制数

问题描述

如何进行减法运算?

确定停止条件-您希望while循环继续进行,直到两个数字a,b和进位零为止。换句话说,条件应该是||。 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;
        }

解决方法

#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
 
int main(int argc,char ** argv)
{
    int a[4]={5,6,0},b[4]={3,4,5,7},c[4]={0}; 
    int point=0; 
    for(int i=3;i>-1;i--) 
    {
        if(a[i]==0)
        {
            for(int j=3;j>-1;j--)   
            {
                if(a[j]!=0 && point==0) 
                {
                    a[j]=a[j]-1; 
                    point=1; 
                    c[i]=8-b[i]; 
                    break; 
                }
                c[i]=7-b[i];
            }
        }
        else
        {
            c[i]=a[i]-b[i]; 
        }
    }
    for(int i=0;i<4;i++)
    {
        cout<<c[i];
    }
}
,
#include <stdio.h>
#include <stdlib.h>

int main()
{
     int a,b,c;
     printf("Enter 1st number: ");
     scanf("%o",&a);
     printf("Enter 2nd number: ");
     scanf("%o",&b);
     c=a-b;
     printf("octal subtraction=%o",c);
}