/* * Author:haoGeDaiWo 这个算法其实很简单,就是先将fload数转化为整数,记录点后面几个数。 然后计算用字符数组想成,这个基本上是模拟人的怎么计算的。 在计算过程中吧前面的零 和后面的零给取消吊 * File:text.cpp * Time:2013/3/15 12:46:12 */ #include <cstdio> #include <cstring> #include <cmath> #include <cstdlib> #include <iostream> #include <fstream> #include <string> #include <sstream> #include <algorithm> #include <vector> #include <stack> #include <queue> #include <set> #include <map> #define MAX 200 using namespace std; #define SZ(v) ((int)(v).size()) char* cut_zero(char *res) { int headZero; int len = strlen(res); for (headZero = 0; headZero < len-1; headZero++) if (res[headZero]!='0') break; if(headZero) for (int i = 0; i <= len; i++) res[i] = res[i+headZero];//将前面的零全部去掉 return res; } char *big_mutiply(char a[], char b[]) { int la = strlen(a);//两个想成数字的长度 int lb = strlen(b);// int r[MAX] = {0};//申请一个int数组为了存数据 char* res = new char [MAX];//字符数组 int head = 0; for (int i = 0; i < la; i++) for (int j = 0; j < lb; j++) r[i+j] += (a[i]-'0')*(b[j]-'0');//基本上多少位想成就应该在后面多少位 for (int i = la + lb - 2; i >= 0; i--) { if (i == 0) { head = r[0]/10;//下面是进位操作 模拟人的计算方式 r[0] = r[0]%10; } else { r[i-1] += r[i]/10; r[i] = r[i]%10; } } if (head == 0) { for (int i = 0; i < la + lb -1; i++) res[i] = r[i]+'0';//现在是将int转化为char; res[la + lb - 1] = '\0'; } else { //如果首位进一的话后面全部往后移首位加上head for (int i = la + lb - 2; i >= 0; i--) res[i+1] = r[i]+'0'; res[0] = head + '0'; res[la + lb] = '\0'; } return cut_zero(res); } char *big_pow(char a[], int n) { if (n == 0) return "1"; if (n == 1) return cut_zero(a); if (n % 2 == 0) return big_mutiply(big_pow(a, n/2),big_pow(a, n/2));//将他们分解后在想成 else return big_mutiply(big_pow(a, n/2),big_pow(a, n/2+1)); } char* double_pow(char s[], int n) { int dot = 0; char* s2 = new char[MAX];//申请一个足够长的char字符组 int len = strlen(s); for (int i = 0, j = 0; i <= len; i++) { if (s[i] == '.') dot = (len-i-1)*n;//记录点的位置并且算出平后应该有个小数 else s2[j++] = s[i];//将s转化为整数 } strcpy(s2, big_pow(s2, n));// if (dot == 0) return s2;//如果是整数直接返回 len = strlen(s2); if (len >= dot)//如果是大于一的整数 { for (int i = len; i >= len - dot; i--) s2[i+1] = s2[i]; s2[len-dot] = '.'; } else { for (int i = len; i>= 0; i--)//如果是小于1的小数 s2[i+dot-len+1] = s2[i]; for (int i = 1; i <= dot - len; i++) s2[i] = '0'; s2[0] = '.'; } for (int i = strlen(s2)-1; i >= 0; i--)//将小数点后面的零给减少 { if (s2[i] == '0') { s2[i] = '\0'; } else { if (s2[i] == '.') s2[i] = '\0'; break; } } return s2; } int main() { char s[10]; int n; while(cin >> s >> n)/*输入数字 s是数字 n是平方数*/ { cout << double_pow(s, n) << endl; } // system("pause"); return 0; }
poj1001算法(C++实现)
最新推荐文章于 2024-07-13 16:30:23 发布