大數減法算法
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
// 功能:實現兩個大數減法運算
// 參數:source1--被減數
// source2--減數
// result --計算結果
// 返回值:計算結果為正數,返回'+',否則返回'-'
char Minus(char *source1, char *source2, char *result)
{
int length1 = strlen(source1); // 被減數的長度
int length2 = strlen(source2); // 減數的長度
int i, j, k = 0;
int temp; // 臨時存放位相減的結果
int bit = 0; // 借位,1表示需要借位,0表示不需要借位
char ch; // 用於交換
for (i = length1 - 1, j = length2 - 1; i >= 0 && j >= 0; --i, --j)
{
// 計算兩個位之間的差值,同時要考慮借位
temp = (source1[i] - '0') - (source2[j] - '0') - bit;
if (temp < 0) // 需要借位
{
bit = 1;
result[k++] = temp + 10 + '0';
}
else// 不需要借位
{
bit = 0;
result[k++] = temp + '0';
}
}
while (i >= 0) // length1 > length2的情況,結果為正數,將剩餘數據賦值給計算結果數組
{
temp = source1[i--] - '0' - bit;
if (temp < 0) // 需要借位
{
bit = 1;
result[k++] = temp + 10 + '0';
}
else
{
bit = 0;
result[k++] = temp + '0';
}
}
while (j >= 0)// length1 < length2的情況,結果為負數,將剩餘數據賦值給計算結果數組
{
temp = 10 - bit - (source2[j--] - '0');
result[k++] = temp + '0';
}
// 對仍有進位的情況考慮,主要分兩種:一種是strlen(p1)<strlen(p2),另一種是p1-p2<0,這兩種情況bit為1
if (bit == 1)
{
// 最低位肯定不會被借位,所以不需要減去借位
// 隻會向高位借位
result[0] = 10 - (result[0] - '0') + '0';
for (i = 1; i < k; i++)
{
result[i] = 10 - (result[i] - '0') - bit + '0';
}
}
for (i = k - 1, j = 0; i >= j; --i, ++j)
{
ch = result[i];
result[i] = result[j];
result[j] = ch;
}
result[k] = '\0';
if (bit == 1)
{
return '-';
}
else
{
return '+';
}
}
int main()
{
char source1[1000];
char source2[1000];
char result[1001];
char op;
scanf("%s%s", source1, source2);
op = Minus(source1, source2, result);
if (op == '-')
{
printf("-");
}
printf("%s\n", result);
return 0;
}
最後更新:2017-04-03 18:52:02