在 c 中创建一个计算器,它只能使用函数 printf 和 putchar,并且可以取非常大的整数

Creating a calculator in c that can ONLY use the functions printf and putchar, and can take very large large integers

Usage: ./calculator.c <operand one> <operator> <operand two>

Ope运行d 一和二必须是大于等于零的正整数。它们每个最多可以有 999 位,因此它们的总和最多可以有 1000 位。我们可以假设没有 ope运行ds 会以 0 开头,例如像 0009738 这样的东西不会被传递。我们只想处理此计算器的加法。 除 printf 和 putchar 外,不能使用其他函数。

我已经处理了其中的大部分,但我在处理最后一部分时遇到了问题。检查运算符是否为“+”非常简单。我通过 运行 while 在每个 ope运行ds 上循环检查初始参数以查看它们是否为正整数,如下所示:

while (argv[1][i] != '[=10=]'){
    if(argv[1][i]>57 || argv[1][i]<48){
.....Printing appropriate error messaage 
return;
   }
} 

我 运行 每个 ope运行ds 上的上述代码,还为每个 ope运行ds 包括了一个计数器,它会告诉我每个有多少位数。此时我有 int max,这是我通过比较计数器得到的。我对添加数字的算法有一个想法(使用 mod 10 得到将放置的数字,然后除以 10 得到进位)。我初始化了三个数组如下:

char first [max +1];
char second [max + 1];
char sum [max + 1];

我只是不知道如何从这里实现 this/move 转发。有人可以帮帮我吗?我必须再次提醒您,可以使用的 only 函数是 printf 和 putchar,这使得这与我在 SO 上经历的多个问题不同。

假设你已经计算出两个操作数的位数,你可以从op1和op2的两个字符数组的末尾循环,将每个char ascii转换为int逐位相加然后转换回 ascii 并存储在输出数组中,同时保留余数。如果输出大小等于单独的 if 条件中的最大可能大小,我会处理这种情况,如下所示:

//f_d num of digits of 1st operand
//s_d num of digits of 2nd operand
int sum=0,ind=0,max=0;
max=(f_d>s_d)?f_d:s_d;
while(ind<max){
    sum=sum/10; //Remainder
    if(f_d!=0) {sum+=argv[1][(f_d--)-1]-48};
    if(s_d!=0) {sum+=argv[3][(s_d--)-1]-48};
    output[max-1-ind++]=(sum%10)+48;
}
output[max]='[=10=]';
if (sum/10!=0){
    int ind=max+1;
    while(ind!=0){
        output[ind--]=output[ind-1];
    }
    output[0]=sum/10+48;
}