大数减法
【摘要】 #include <stdio.h>#include <string.h> #define N 100 void charstoint(int a[], char s[]){ int i; int len = strlen(s); memset(a,0,4*N); //整型占4个字节 for (i=0; i<len; i++) { //...
-
#include <stdio.h>
-
#include <string.h>
-
-
#define N 100
-
-
void charstoint(int a[], char s[])
-
{
-
int i;
-
int len = strlen(s);
-
memset(a,0,4*N); //整型占4个字节
-
-
-
for (i=0; i<len; i++)
-
{
-
//不考虑负数与非数字字符的情况
-
a[len-1-i] = s[i] - '0'; //将每一个字符转化为数字逆序存放在整型数组中
-
}
-
}
-
-
void sub(int a[], int b[], int c[])
-
{
-
int i = 0;
-
int j = N-1;
-
int carry = 0;
-
memset(c,0,4*N);
-
while(a[j]==0 && b[j] == 0 ) //去掉多余的0
-
{
-
-
j--;
-
}
-
for (i=0; i<=j; i++)
-
{
-
if (a[i]-carry < b[i])
-
{
-
c[i] = a[i]-b[i]+10 - carry;
-
carry = 1;
-
}
-
-
else
-
{
-
-
c[i] = a[i] - b[i] - carry;
-
carry = 0;
-
}
-
}
-
}
-
-
-
int main()
-
{
-
int i,j = N-1;
-
int a[N],b[N],c[N];
-
char s1[N],s2[N];
-
-
-
printf("input the first number:");
-
gets(s1);
-
printf("input the second number:");
-
gets(s2);
-
-
-
charstoint(a,s1);
-
charstoint(b,s2);
-
-
if (strlen(s1) > strlen(s2))
-
{
-
sub(a,b,c);
-
}
-
-
else if (strlen(s1) == strlen(s2))
-
{
-
if (strcmp(s1,s2)>=0)
-
{
-
sub(a,b,c);
-
}
-
else
-
{
-
sub(b,a,c);
-
printf("-");
-
}
-
}
-
-
else
-
{
-
sub(b,a,c);
-
printf("-");
-
}
-
-
while(c[j]==0 && j>0) //去掉多余的0
-
{
-
j--;
-
}
-
for (i=j; i>=0; --i) //打印结果
-
{
-
printf("%d",c[i]);
-
}
-
-
-
printf("\n");
-
-
-
return 0;
-
}
文章来源: blog.csdn.net,作者:悦来客栈的老板,版权归原作者所有,如需转载,请联系作者。
原文链接:blog.csdn.net/qq523176585/article/details/11594057
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)