题目链接:http://poj.org/problem?id=1001
要注意的细节都在代码注释上面,只要正常的做矩阵乘法就行了;(小数点的位置,前导零和末尾0等等)
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<cmath>
#include<queue>
#include<map>
#include<stack>
#include<sstream>
#include<vector>
#include<string>
#include<set>
using namespace std;
#define IOS ios::sync_with_stdio(false); cin.tie(0);
#define REP(i,n) for(int i=0;i<n;++i)
int read(){
int r=0,f=1;char p=getchar();
while(p>'9'||p<'0'){if(p=='-')f=-1;p=getchar();}
while(p>='0'&&p<='9'){r=r*10+p-48;p=getchar();}return r*f;
}
typedef long long ll;
typedef unsigned long long ull;
const int Maxn = 510;
const long long LINF = 1e18;
const int INF = 0x3f3f3f3f;
const int Mod = 1e6+7;
const double PI = acos(-1.0);
int ans[Maxn],a[Maxn],tmp[Maxn];
char s[Maxn];
int main (void)
{
char b[20];
int n;
while (scanf("%s%d",s,&n) != EOF) {
gets(b); // 读入回车和多余空格
int m = strlen(s),pos = -1,cnt = 0,x = n-1;
memset(ans,0,sizeof(ans));
for (int i = m-1; i >= 0; --i) {
if(s[i] == '.') { pos = (m-1)-i; continue; } // 记录小数点的位置
ans[cnt] = a[cnt] = s[i]-'0';
cnt++;
}
int M = cnt;
while (x--) {
memcpy(tmp,ans,sizeof(tmp)); // 让a和tmp相乘,结果存到ans中,下一轮在把ans的值复制给tmp
memset(ans,0,sizeof(ans)); // ans清零
int q;
for (int i = 0; i < cnt; ++i) {
q = i;
for (int j = 0; j < M; ++j) {
ans[q]+=a[i]*tmp[j];
if(ans[q] > 9) ans[q+1]+=ans[q]/10;
ans[q++]%=10;
}
}
M = max(M,q); // 记录ans的长度
if(ans[q] && M == q) M++;
}
if(pos > -1) pos*=n; // 小数点的位数乘以平方数为结果的小数点的位置
else pos = 0;
int p;
cnt = 0; p = M-1;
while(!ans[p--]); // 把前导零去掉
for (int i = p+1; i >= pos; --i) s[cnt++] = (char)(ans[i]+'0');
s[cnt] = '\0';
if(strlen(s)) printf("%s",s); // 如果s为空就不用输出
if(pos) {
cnt = 0; p = 0;
while (!ans[p++]); // 把末尾的0去掉
for (int i = pos-1; i >= p-1; --i) s[cnt++] = (char)(ans[i]+'0');
s[cnt] = '\0';
if(strlen(s)) printf(".%s",s); // 为空就不用输出,比如整数的时候
}
printf("\n");
}
return 0;
}