C语言高精度计算源代码合集

编程入门 行业动态 更新时间:2024-10-06 12:24:29

C语言高精度计算源代码<a href=https://www.elefans.com/category/jswz/34/1769982.html style=合集"/>

C语言高精度计算源代码合集

首先说明,自己写的源代码不一定为最优解,只是我平时用的方法,如果有人能给出更好的建议,可以在下方评论,借鉴一下~

目录

数据定义

常见输入数据转换(int,char*)

加法运算

减法运算

乘法运算

输出函数


数据定义

(cnt为整数位数,v存储着每一位的值,sign表示符号 )

typedef struct{int cnt,v[501],sign;}BIGINT;

//要注意,v中存放数值是从数字的个位开始倒序存放的,是为了后续的计算方便。

常见输入数据转换(int,char*)

//int转换成BIGINT

BIGINT int2BIG(int x)  //int 转换成BIGINT
{BIGINT R= {0,{0},1};if(x<0){R.sign=-1;x=-x;}do{R.v[Rt++]=x%10;x/=10;} while (x>0);return R;
}

//char*转换成BIGINT

BIGINT char2BIG(char* s)
{int len=strlen(s);BIGINT R={len,{0},1};int i=len-1,j=0;if (s[0]=='-') {R.sign=-1;Rt=len-1;}while(i>=0&&s[i]!='-'){R.v[j++]=s[i]-'0';i--;}return R;
}

加法运算

//当涉及符号不一样时 ,就要转变为大整数的减法运算

BIGINT BIGADD(BIGINT s,BIGINT t)
{if(st==0) return t;if(tt==0) return s;BIGINT R={0,{0},1};if(s.sign*t.sign<0){if(s.sign==-1) R=BIGSUB(t,s);else R=BIGSUB(s,t);}else{R.sign =s.sign;int i,carry=0;for(i=0 ;i<st&&i<tt;i++){int temp = s.v[i]+t.v[i]+carry;R.v[i]=temp%10;carry=temp/10;}while(i<tt){int temp =t.v[i]+carry;R.v[i++] =temp%10;carry = temp/10;}while (i<st){int temp =s.v[i]+carry;R.v[i++]=temp%10;carry = temp/10;}if(carry){R.v[i++]=carry%10;}Rt=i;}return R;}

减法运算

int cmp(BIGINT s,BIGINT t)
{int n =(st>tt)?st:tt;for(int i=n-1;i>=0;i--){if(*(s.v+i)>*(t.v+i)) return 1;else if(*(s.v+i)<*(t.v+i)) return -1;}return 0;
}
void SUB(BIGINT* s,BIGINT* t,BIGINT* result)
{int n=(s->cnt>t->cnt)?s->cnt:t->cnt;result->cnt=n;int carry=0,i;for(i=0;i<n;i++){if((*(s->v+i)+carry)<(*(t->v+i))){*(result->v+i)=*(s->v+i)+10+carry-*(t->v+i);carry=-1;}else {*(result->v+i)=*(s->v+i)+carry-*(t->v+i);carry=0;}}for (int i=n-1;i>=0&&result->v[i]==0;i--) result->cnt--;
}BIGINT BIGSUB (BIGINT s,BIGINT t)
{BIGINT R={0,{0},1};if (cmp(s,t)>=0){R.sign=1;SUB(&s,&t,&R);}else{R.sign=-1;SUB(&t,&s,&R);}return R;
}

乘法运算

BIGINT BIGMUL(BIGINT S,BIGINT T)
{BIGINT R={0,{0},1};if(St==0||Tt==0) return R;Rt = St+Tt;R.sign =S.sign*T.sign;for(int i=0;i<Tt;i++){int j,t,k;int carry=0;for(j=0;j<St;j++){t=S.v[j]*T.v[i]+carry+R.v[i+j];R.v[i+j] = t%10;carry=t/10;}k=i+j;while (carry>0){t=carry+R.v[k];R.v[k]=t%10;carry=t/10;k++;}}if (R.v[St+Tt-1]==0) Rt--;return R;
}

输出函数

void BIGoutput(BIGINT x)
{if(x.sign==-1) printf("-");for(int i=xt-1;i>=0;i--) printf("%d",x.v[i]);
}

更多推荐

C语言高精度计算源代码合集

本文发布于:2024-02-06 20:15:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1751266.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:合集   源代码   语言

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!