- Source Code
// Exponentiation.cpp : Defines the entry point for the console application. // #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <string.h> #include <stdlib.h> #define MAX_INTEGER 49 #define MAX_DECIMAL 101 const int zero[200] = { 0 }; class longnumber{ public: int upperbound, lowerbound; int integer[MAX_INTEGER]; int decimal[MAX_DECIMAL]; bool isinteger; //构造函数 longnumber() : upperbound(0), lowerbound(0), isinteger(false) { memcpy(integer, zero, MAX_INTEGER*sizeof(int)); memcpy(decimal, zero, MAX_DECIMAL*sizeof(int)); } ~longnumber() { upperbound = 0; lowerbound = 0; isinteger = false; memcpy(integer, zero, MAX_INTEGER*sizeof(int)); memcpy(decimal, zero, MAX_DECIMAL*sizeof(int)); } void setDecimal(int i, int a){ this->decimal[i] = a; } void setInteger(int i, int a){ this->integer[i] = a; } void setUpperbound(){ int i; for (i = MAX_INTEGER - 1; integer[i] == 0 && i >= 0; i--); if (integer[i] != 0) { upperbound = i + 1; } else { upperbound = i; } } void setLowerbound(){ int i; for (i = MAX_DECIMAL - 1; decimal[i] == 0 && i>0; i--); lowerbound = i; } int getUpperbound(){ return this->upperbound; } int getLowerbound(){ return this->lowerbound; } void isInteger(bool f){ isinteger = (lowerbound == 0); } //大数乘法 longnumber operator *(longnumber &rhs){ longnumber temp; //存放结果 int i, j, tempres; //tempres为临时相乘结果 for (i = -this->lowerbound; i <= this->upperbound; i++) { for (j = -rhs.lowerbound; j <= rhs.upperbound; j++) { tempres = *getpos(this, i) * *getpos(&rhs, j); *getpos(&temp, i + j) += tempres % 10; *getpos(&temp, i + j + 1) = *getpos(&temp, i + j + 1) + tempres / 10 + *getpos(&temp, i + j) / 10; *getpos(&temp, i + j) %= 10; *getpos(&temp, i + j + 2) += *getpos(&temp, i + j + 1) / 10; *getpos(&temp, i + j + 1) %= 10; } } temp.setUpperbound(); temp.setLowerbound(); return temp; } //a为10的幂位数,范围为(...3,2,1,0,-1,-2,-3...),返回指向大数ln的整数部分integer[]、或小数部分decimal[]的int的指针 static int* getpos(longnumber *ln, int a){ int* p; if (a >= 0){ p = ln->integer + a; return p; } else { p = ln->decimal - a; return p; } } void out() { int i; for (i = upperbound - 1; i >= 0; i--) { printf("%d", integer[i]); } if(lowerbound!=0) printf("."); for (i = 1; i <= lowerbound; i++) { printf("%d", decimal[i]); } putchar('\n'); } private: }; int main(int argc, char* argv[]) { char input[5]; int i, j, n; char* pChar; longnumber a, res; while (scanf("%s %d", input, &n) == 2) { char* pDot = strchr(input, '.'); for (i = 0, pChar = pDot - 1; pChar >= input; i++, pChar--){ a.setInteger(i, *pChar - 48); }; a.setUpperbound(); for (j = 1, pChar = pDot + 1; pChar <= (input + strlen(input) - 1); j++, pChar++){ a.setDecimal(j, *pChar - 48); } a.setLowerbound(); res = a; for (i = 1; i < n; i++){ res = res * a; } res.out(); a.~longnumber(); res.~longnumber(); } return 0; }
C++1001
最新推荐文章于 2022-08-25 21:39:28 发布