有没有C语言的大神,帮我改一下这个代码,要求实现高精度减法.借位没做出来 5
#include<stdio.h>#include<string.h>typedefstruct{inta[400];intb[400];}NUM;voidformat_...
#include <stdio.h>
#include <string.h>
typedef struct
{
int a[400];
int b[400];
}NUM;
void format_num(NUM *n, char *str)
{
char *p_dot=NULL;
char *p;
int i=0;
memset(n,0,sizeof(*n));//0,k
for(p=str; *p;p++)
if(*p=='.') break;
if(*p)p_dot = p;
p--;
while(p>=str)
{
n->a[i++] = *p-- - '0';
}
p=p_dot;
if(p==NULL) return;
i=0;
p++;
while(*p)
n->b[i++] = *p++ - '0';
}
void print_num(NUM *n)
{
int i, j;
for(i = sizeof(n->a)/sizeof(n->a[0])-1; i>=0;i--)
if(n->a[i]) break;
if(i>=0)
for(;i>=0;i--)
printf("%d",n->a[i]);
else printf("0");
for(i = sizeof(n->b)/sizeof(n->b[0])-1; i>=0;i--)
if(n->b[i]) break;
if(i>=0)
{
printf(".");
for(j = 0; j <= i; j ++)
printf("%d", n->b[j]);
}
}
void add(NUM *a, NUM *b, NUM *c)
{
int t=0;
int i,n;
for(i=sizeof(a->b)/sizeof(a->b[0])-1;i>=0;i--)
{
if(a->b[i]>=b->b[i])
{
c->b[i] =a->b[i] - b->b[i];
}
else
{
c->b[i]=a->b[i]+10-b->b[i];
a->b[i-1]--;
}
}
for(i=0;i<sizeof(a->a)/sizeof(a->a[0]-1); i ++)
{
if(a->a[i]>=b->a[i])
{
c->a[i]=a->a[i] - b->a[i];
}
else
{
c->a[i] =a->a[i]+10-b->a[i];
a->a[i+1]--;
}
}
}
int main()
{
char sa[400], sb[400];
NUM a,b,c;
scanf("%s%s", sa,sb);
format_num(&a, sa);
format_num(&b,sb);
print_num(&a);
printf(" - ");
print_num(&b);
printf(" = ");
add(&a,&b,&c);
print_num(&c);
printf("\n");
return 0;
} 展开
#include <string.h>
typedef struct
{
int a[400];
int b[400];
}NUM;
void format_num(NUM *n, char *str)
{
char *p_dot=NULL;
char *p;
int i=0;
memset(n,0,sizeof(*n));//0,k
for(p=str; *p;p++)
if(*p=='.') break;
if(*p)p_dot = p;
p--;
while(p>=str)
{
n->a[i++] = *p-- - '0';
}
p=p_dot;
if(p==NULL) return;
i=0;
p++;
while(*p)
n->b[i++] = *p++ - '0';
}
void print_num(NUM *n)
{
int i, j;
for(i = sizeof(n->a)/sizeof(n->a[0])-1; i>=0;i--)
if(n->a[i]) break;
if(i>=0)
for(;i>=0;i--)
printf("%d",n->a[i]);
else printf("0");
for(i = sizeof(n->b)/sizeof(n->b[0])-1; i>=0;i--)
if(n->b[i]) break;
if(i>=0)
{
printf(".");
for(j = 0; j <= i; j ++)
printf("%d", n->b[j]);
}
}
void add(NUM *a, NUM *b, NUM *c)
{
int t=0;
int i,n;
for(i=sizeof(a->b)/sizeof(a->b[0])-1;i>=0;i--)
{
if(a->b[i]>=b->b[i])
{
c->b[i] =a->b[i] - b->b[i];
}
else
{
c->b[i]=a->b[i]+10-b->b[i];
a->b[i-1]--;
}
}
for(i=0;i<sizeof(a->a)/sizeof(a->a[0]-1); i ++)
{
if(a->a[i]>=b->a[i])
{
c->a[i]=a->a[i] - b->a[i];
}
else
{
c->a[i] =a->a[i]+10-b->a[i];
a->a[i+1]--;
}
}
}
int main()
{
char sa[400], sb[400];
NUM a,b,c;
scanf("%s%s", sa,sb);
format_num(&a, sa);
format_num(&b,sb);
print_num(&a);
printf(" - ");
print_num(&b);
printf(" = ");
add(&a,&b,&c);
print_num(&c);
printf("\n");
return 0;
} 展开
1个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询