下面给出高精度除法的源代码,可以实现任意除法计算至循环。
#include<iostream>#include<Windows.h>using namespace std;bool CheckIfLoop(int *remainarr, int length, int remain,int loop);int main(){ int dividend, divisor, remain=0,k=0;//dividend为被除数,divisor为除数,remain为余数,k为当前余数列表 cout << "请输入被除数与除数:"; cin >> dividend >> divisor; int *remainarr = new int[512]; cout << "结果为:"; cout << dividend / divisor; if (remain != 0 || dividend%divisor!=0)//余数为0,除尽,结束循环 { cout << ".";//输出小数点 } remain = dividend%divisor; while (CheckIfLoop(remainarr, 512, remain,k) && remain!=0) { remainarr[k] = remain; remain *= 10; cout << remain / divisor; remain %= divisor; if (k < 512) { k++; } } system("pause"); return 0;}bool CheckIfLoop(int *remainarr, int length, int remain, int loop){ static int looptime = 0; for (int i = 0; i < length; i++) { if (remainarr[i] == remain) { cout << "(无限循环开始,周期:" << looptime << ")"<<endl; remainarr[loop] = remain; return 0; } } looptime++; return 1;}说明,余数列表设为512位是根据相关定理,所有分数都是有理数,并且是循环小数,开始我把余数列表的长度定位除数的大小,但是后来发现这样在余数很大的情况下十分占用内存,所以设定为了512,在一定范围内有效。
新闻热点
疑难解答