比較難處理的一題
這邊要將前面和後面的0通通去掉
在 print 函數裡下了不少工夫
大數運算參考 演算法筆記 - Big Number
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <cstdio>
#include <cstring>
#include <iostream>
#define maxn 1000
using namespace std;
// print
int dot;
void print(int a[maxn]){
int i=maxn-1; // 要印的數字位置
int stop=0;
int dot_appear=0;
while(i>=0 && a[i]=='\0' && i+1>dot) i--; // 數字開頭的零都不印
if(i<0)cout << '0';
else while(i>=0 && stop!=1) { //stop不等於1時,持續輸出數字
if(i+1==dot){
cout << '.';
dot_appear=1;
}
if(dot_appear==1){ //從輸出小數點後,針對後面的數字做檢查
stop=1; //若後面皆為0,則stop=1
for(int j=i;j>=0;j--){
if(a[j]!=0){ //若後面有非0者,stop=0
stop=0; break;
}
}
}
if(stop!=1)cout << a[i];
i--;
}
}
// c = a * b;
void mul(int a[maxn], int b[maxn], int c[maxn]){
for (int i=0; i<maxn; i++)
c[i] = 0;
for (int i=0; i<maxn; i++)
for (int j=0; j<maxn; j++)
if (i+j < maxn)
c[i+j] += a[i] * b[j];
for (int i=0; i<maxn-1; i++) // 一口氣進位
{
c[i+1] += c[i] / 10;
c[i] %= 10;
}
}
char input[maxn];
int a[maxn],b[maxn],result[maxn];
int main(){
freopen("input.txt","r",stdin);
for(int i=0;i<maxn;i++)a[i]='\0';
for(int i=0;i<maxn;i++)b[i]='\0';
for(int i=0;i<maxn;i++)result[i]='\0';
while(scanf("%s",&input)!=EOF){
//紀錄小數點後有幾位
dot=0;
int len = strlen(input);
for(int i=len-1;i>0;i--){
if(input[i]=='.')break;
dot++;
}
//change input into integer array
for(int i=0;i<len;i++){
a[i]=input[len-i-1]-48;
}
//將小數點去掉
for(int i=dot;i<len;i++){
a[i]=a[i+1];
a[i+1]=0;
}
for(int i=0;i<maxn;i++)b[i]=a[i]; //將a複製給b
int n;
scanf("%d",&n);
dot *= n; //乘幾次,小數點後位數就加倍幾次
n--;
while(n--){
mul(a,b,result); //每次的b乘給a
for(int i=0;i<maxn;i++)b[i]=result[i]; //將result複製給b
}
/*
for(int i=0;i<maxn;i++){
if(result[i]==0)printf("%d",result[i]);
else if(result[i]=='\0');
else printf("%d",result[i]);
}
*/
//printf("\n");
print(result);
printf("\n");
}
return 0;
}
沒有留言:
發佈留言