今天主要学习了高精度算法,在理解高精度算法时,我们可以回想一下我们在小学学习整数相加时的格式。从个位开始对齐,每一位数一一对应。
高精度加法
当我们的各个位数相加时,向较高的一位进一。
代码实现:
#include<stdio.h>
#include<string.h>struct bign //bign即big number的简写,此处先构造一个函数,用于储存每一个大整数
{int d[10000];int lenth;bign() {memset(d , 0, sizeof(d));lenth = 0;}
};bign change(char str[]) //将整数转化为大整数
{bign a;a.lenth = strlen(str);for(int i = 0; i < a.lenth; i++){a.d[i] = str[a.lenth - i - 1] - '0';}return a;
}
bign add(bign a, bign b){ //高精度a + bbign c;int carry = 0; //carry是进位for(int i = 0; i < a.lenth || i < b.lenth; i++){ int temp = a.d[i] + b.d[i] + carry; //两个对应位与进位相加c.d[c.lenth++] = temp % 10; //个位数为该位结果carry = temp / 10; //十位数为新的进位}if(carry != 0){ //如果最后的进位不为0,就直接赋给结果的最高位c.d[c.lenth++] = carry;}return c;
}
void print(bign a){ //输出大整数for(int i = a.lenth -1; i >=0; i--){printf("%d",a.d[i]);}
}
int main()
{char str1[1000], str2[1000];scanf("%s %s", str1, str2);bign a = change(str1);bign b = change(str2);print(add(a, b));return 0;
}
明天继续其他的高精度算法的研究