gpt4 book ai didi

C 中大整型加法中的进位数字/填充

转载 作者:行者123 更新时间:2023-11-30 17:36:29 29 4
gpt4 key购买 nike

我正在尝试添加用户输入的两个大整数作为字符串。当两个输入字符串的长度不同时,我尝试用零填充较短的数字,但它不起作用。因此,如果我输入 456 和 7,它会给出 3,前面有一些随机字符。感谢您的任何建议!

void reverse(char *start, char *end)
{
int l ;
int len = strlen(start);
for (l=0;l<len;l++)
end[l] = start[len-l-1];
end[len] = '\0';

}

void add (char *x, char *y, char *sum)
{
char XA[MAXDIGITS];
char YA[MAXDIGITS];
char tempa[MAXDIGITS];
int xa_len, ya_len, xa1, ya1, carry, addition, p, q;
int m = 0;
int n = -1;
xa_len=strlen(x);
ya_len=strlen(y);
reverse(x,XA);
reverse(y,YA);
m = (xa_len > ya_len)?xa_len:ya_len;
for(xa1=0;xa1<=m;xa1++)
tempa[xa1] = '0';
tempa[xa1] = '\0';
if(xa_len>ya_len)
{
for(p=(xa_len-ya_len);p=<m;p++) YA[p]='0';
YA[p] = '\0';
}
if(ya_len>xa_len)
{
for(q=(xa_len-ya_len);q=<m;q++) XA[q]='0';
XA[p] = '\0';
}
for(xa1=0;xa1<=m;xa1++)
{
addition=(XA[xa1]-'0')+(YA[xa1]-'0')+carry;
tempa[xa1] = addition%10+'0';
carry = addition/10;
if (n<xa1) n=xa1;
}
printf("%d", carry);
for(;n>0 && tempa[n]=='0';n--)
tempa[n+1]='\0';
reverse(tempa,sum);
}

这就是我打印输出的方式

add (x,y,addition);
int length=(strlen(addition));
printf("Sum is ");
for(k=0;k<length;k++) printf("%c",addition[k]);

最佳答案

当然carry必须初始化。

无法执行您的代码。对 reverse() 的调用可以通过简单地以相反方向运行循环来完成。此外,最后的执行似乎不会影响结果。建议的代码如下:

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

char *str_add(const char *a, const char *b) {
size_t alen = a == NULL ? 0 : strlen(a);
size_t blen = b == NULL ? 0 : strlen(b);
if (blen > alen) {
const char *t = a; a = b; b = t;
size_t tlen = alen; alen = blen; blen = tlen;
}
size_t clen = blen + 1;
int carry = 0;
char *c = malloc(clen + 1); // 1 extra
const char *ap = &a[alen];
const char *bp = &b[blen];
char *cp = &c[clen];
*cp = '\0';
while (bp > b) {
int sum = *(--ap) - '0' + *(--bp) - '0' + carry;
carry = 0;
if (sum >= 10) {
sum -= 10;
carry++;
}
*(--cp) = sum + '0';
}
while (ap > a) {
int sum = *(--ap) - '0' + carry;
carry = 0;
if (sum >= 10) {
sum -= 10;
carry++;
}
*(--cp) = sum + '0';
}
if (carry) {
memmove(&cp[1], &cp[0], clen);
*cp = carry + '0';
}
return cp;
}

void test_add(const char *a, const char *b) {
char *sum = str_add(a,b);
printf("%s + %s = %s\n", a, b, sum);
free(sum);
}

关于C 中大整型加法中的进位数字/填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22670424/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com