C编程:使用ASCII码进行字符串计算

4
如果我将像这样的字符字符串中的数字存储在数组 x[100]y[100] 中,
x[100] '1' '0' '0' '0' '\0'
y[100] '9' '9' '\0'

添加的结果也应该被存储为字符串。
result[100] '1' '0' '9' '9' '\0'

我尝试使用ASCII码来解决这个问题,例如:

char number[2] = {'1','2'};
char result;

result = (number[0] - '0') + (number[1] - '0') + '0';

但是我在调整x[100]y[100]的数字时遇到了困难。

我真的非常需要你的帮助 :(

5个回答

2
你可以坚持避免使用库函数将字符串转换为数字,反之亦然,就像@sjsam所提到的那样。
如果你仔细想一想,数字实际上从LSD(最低有效位,不是酸)或右侧开始。因此,在每个数组的最后一个字符之前开始循环,直到闭合的\0并向后迭代。这并不容易,但这就是atoi()的工作原理。
罗马人从左到右写作非常不幸,但这就是这个问题的根本原因。否则,从右到左阿拉伯数字的集成将变得更加容易。
讨论罗马数字的愚蠢超出了本答案的范围,让我们只说他们缺乏零阻止了任何程序以成功的退出状态结束,这反过来导致了罗马帝国的崩溃。

1
很奇怪。在我接触到的所有文献中,罗马帝国程序都通过 const char* 返回它们的退出代码,但是朱利叶斯·凯撒忘记包含一个空终止符...剩下的故事就不用说了。 - Daniel Kamil Kozar

1

不需要逐字节添加,您可以使用函数atoi将字符串转换为整数,一旦计算出总和,您可以使用itoa/snprintf将总和(整数)转换为其字符串表示形式。

请参阅下面的示例:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int main(void)
{
        char buffer[100];
        int no1,no2,no3;

        char number1[] = {'1','0','0','0','\0'};
        char number2[] = {'9','0','0','\0'};

        /* Converting strings to respective integers */
        no1=atoi(number1);
        no2=atoi(number2);

        no3=no1+no2;

        /* Convert integer to a null terminated string
         * You could also use itoa(no3,buffer,10); 
         */


        snprintf(buffer,99,"%d",no3);


        printf("no1 : %d\n",no1);
        printf("no2 : %d\n",no2);
        printf("no3 : %s\n",buffer); // printing the string
        return 0;
}

itoa在一些编译器中不受支持,因此最好使用snprintf

输出

这里buffer是一个以空字符结尾的数组。

{'1','9','0','0','\0'}

我们使用%s格式说明符打印了这个内容。

参考资料

  1. itoa手册。
  2. snprintf手册。

注意

在这个例子中,我将缓冲区大小设置为100。然而,buffer可以容纳的最大字节数取决于您的系统中整数(在您的情况下为有符号整数)所能包含的最大值。(感谢@BLUEPIXY提醒这个问题。 :) )


1
注意:atoi不能用于99位数。 - BLUEPIXY
@BLUEPIXY:我会在这里加上一条注释... 有道理 :) - sjsam
他想使用ASCII字节进行添加。你没有回答所问的问题。 - abelenky
@abelenky:他没有提到他想要一个具体的方法。是吗? - sjsam
我认为问题标题和代码片段已经非常清楚明了。 - abelenky
@sjsam:虽然这对我来说不太清楚:(而且,我只是想用另一种方法。 - sjsam

1

在避免转换为二进制/十进制的情况下求ASCII数字之和:

#include <stdio.h>
#include <string.h>
#include <libc.h>

char *sum(char *x, char *y) {

    size_t x_idx = strlen(x);
    size_t y_idx = strlen(y);
    size_t z_idx = MAX(x_idx, y_idx) + 1;

    char *z = malloc(z_idx + 1);
    char carry = '0';

    while (x_idx > 0 || y_idx > 0 || carry == '1') {

        char digit = carry;

        if (x_idx > 0 && y_idx > 0) {
            digit = (x[--x_idx] + y[--y_idx] + carry) % '0' + '0';
        } else if (x_idx > 0) {
            digit = (x[--x_idx] + carry) % '0' + '0';
        } else if (y_idx > 0) {
            digit = (y[--y_idx] + carry) % '0' + '0';
        }

        carry = (digit > '9') ? '1' : '0';

        if (carry == '1') {
            digit -= 10;
        }

        z[--z_idx] = digit;
    }

    while (z_idx > 0) {
        z[--z_idx] = ' '; // pad for now; for production, shift array
    }

    return z;
}

int main(int argc, char* argv[]) {
    char *x = argv[1];
    char *y = argv[2];
    char *z = sum(x, y);

    printf("%s + %s = %s\n", x, y, z);

    free(z);
}

使用方法

> ./a.out 1000 99
1000 + 99 =  1099
> 
> ./a.out 999 999
999 + 999 = 1998
>

-1
#include <stdio.h>
#include <string.h>

int main(void) {
    char x[100] = "1000";
    char y[100] = "99";
    char result[100+1] = " ";
    int x_i = strlen(x)-1;
    int y_i = strlen(y)-1;
    int r_i = 1 + ((x_i > y_i) ? x_i + 1 : y_i + 1);
    int carray = 0, sum;
    result[r_i] = 0;

    while(--r_i>0){
        if(x_i >= 0 && y_i >= 0)
            sum = x[x_i--] - '0' + y[y_i--] - '0' + carray;
        //else if(x_i < 0 && y_i < 0)
        //  sum = carray;
        else if(y_i < 0)// && x_i >= 0){
            sum = x[x_i--] - '0' + carray;
        else// if (x_i < 0 && y_i >= 0){
            sum = y[y_i--] - '0' + carray;
        carray = sum > 9;
        result[r_i] = sum % 10 + '0';
    }
    if(carray)
        result[0] = '1';
    printf("%s\n", result);
    return 0;
}

-1
这是一些代码,可以给你一个很好的想法。
这可以开始处理进位,但不涵盖所有情况。它应该是一个很好的开始。
#include <stdio.h>
#include <string.h>

int main(void) {
    char y[100] = "1032";
    char x[100] = "2399";
    int carry = 0;

    char* b = (strlen(x) >  strlen(y))? x : y;
    char* s = (strlen(x) <= strlen(y))? x : y;

    for(int i=strlen(s)-1, j=strlen(b)-1; i>=0; --i,--j)
    {
        b[j] = (b[j]+s[i]+carry-'0');
        carry = 0;
        if (b[j] > '9')
        {
            b[j] = (b[j]-'0')%10+'0';
            carry = 1;
        }
    }

    puts(b);
    return 0;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接