Devil_W, 哥给你写的 BigFloat
#include <stdio.h> #include <string.h>
#define MAX_LEN 150
unsigned an1[MAX_LEN];
unsigned an2[MAX_LEN];
unsigned aResult[2*MAX_LEN];
char szBase1[MAX_LEN];
char szBase2[MAX_LEN];
int len1,len2;
void bgMultiply(void)
{
int i, j;
//每一轮都用an1的一位,去和an2各位相乘,从an1的个位开始
for( i = 0;i < len2; i ++ )
{
//用选定的an1的那一位,去乘an2的各位
for( j = 0; j < len1; j ++ )
//两数第i, j位相乘,累加到结果的第i+j位
aResult[i+j] += an2[i]*an1[j];
}
//下面的循环统一处理进位问题
for( i = 0; i < MAX_LEN-1; i ++ )
{
if( aResult[i] >= 10 )
{
aResult[i+1] += aResult[i] / 10;
aResult[i] %= 10;
}
}
}
int main(void)
{
FILE* fp;
int i,j,basePointPos1,baseDecimalDigits1,basePointPos2,baseDecimalDigits2,resultPointPos,resultEndPos,resultBeginPos;
char* p;
while(scanf("%s%s",szBase1, szBase2)>0)
{
basePointPos1 = -1;
baseDecimalDigits1 = 0;
basePointPos2 = -1;
baseDecimalDigits2 = 0;
memset( an1, 0, sizeof(an1));
memset( an2, 0, sizeof(an2));
memset( aResult, 0, sizeof(aResult));
len1 = strlen(szBase1);
//根据小数点位置和末尾0的出现来计算小数位数,同时计算排除末尾0的长度
p = strchr(szBase1,'.');
if(p)
{
basePointPos1 = p-szBase1;
for( i = len1 - 1; szBase1[i]=='0' && i>basePointPos1; i--)
continue;
baseDecimalDigits1 = i-basePointPos1;
len1 = i+1;
}
j = 0;
for( i = len1 - 1;i >= 0 ; i--)
{
if(i==basePointPos1)
continue;
an1[j] = szBase1[i] - '0';
j++;
}
len2 = strlen(szBase2);
//根据小数点位置和末尾0的出现来计算小数位数,同时计算排除末尾0后的长度
p = strchr(szBase2,'.');
if(p)
{
basePointPos2 = p-szBase2;
for( i = len2 - 1; szBase2[i]=='0' && i>basePointPos2; i--)
continue;
baseDecimalDigits2 = i-basePointPos2;
len2 = i+1;
}
j = 0;
for( i = len2 - 1;i >= 0 ; i--)
{
if(i==basePointPos2)
continue;
an2[j] = szBase2[i] - '0';
j++;
}
bgMultiply();
//计算结果中小数点应出现的位置
resultPointPos = baseDecimalDigits1 + baseDecimalDigits2 - 1;
//计算结果的最后一位在数组中的位置
resultEndPos = 0;
for( i = 0; aResult[i]==0 && i<resultPointPos; i++ )
continue;
resultEndPos = i;
//计算结果的最高位在数组中的位置
for( i = MAX_LEN-1; aResult[i]==0 && i>=0; i-- )
continue;
if(resultPointPos>i)
resultBeginPos = resultPointPos;
else
resultBeginPos = i;
fp = fopen("blue.txt", "ab");
for( i = resultBeginPos; i>=resultEndPos ; i-- )
{
if (resultBeginPos == resultEndPos)
{
printf("0");
fprintf(fp,"%d", 0);
}
if ( i == resultPointPos )
{
printf(".");
fprintf(fp,"%c", '.');
}
fprintf(fp,"%d", aResult[i]);
printf("%d", aResult[i]);
}
fprintf(fp,"%s", "\r\n");
fclose(fp);
printf("\n");
}
return 0;
}
样例输入
11.2233445566778899 99.8877665544332211
1122.33445566778899 9988.77665544332211
112233.445566778899 998877.665544332211
11223344.5566778899 9988776655.44332211
1122334455.66778899 998877665544.332211
112233445566.778899 99887766554433.2211
样例输出
1121.07482103740987777903741240815689
11210748.2103740987777903741240815689
112107482103.740987777903741240815689
112107482103740987.777903741240815689
1121074821037409877779.03741240815689
11210748210374098777790374.1240815689
[ 本帖最后由 BlueGuy 于 2010-7-20 22:28 编辑 ]