748 - Exponentiation

题目:748 - Exponentiation


题目大意: 高精度数乘方


解题思路: 先记录小数点的位置,然后去掉前导0,和后面不需要的0,注意数组大小不要开得正好,否则会出现一些不可预知的错误;


#include<stdio.h>
#include<string.h>
#include<iostream>
using namespace std;

const int N = 10000;
char s[10], s1[10];
int  dection , move;


struct begin {

	int len;
	char s[N];
	begin() {
		
		len = 1;
		memset(s, 0 ,sizeof(s));
	}
	begin operator = (const char * num);
	begin operator + (const begin &b);
	begin operator * (const begin & b);
	begin operator += (const begin & b);

}a, ans, sum;

begin begin::operator =(const char * num) {

	move = 0;
	bool bo = 0;
	int k = 0;
	len = strlen(num);

		for( int i = 0; i < len; i++) {

			if(i == dection|| num[len - 1 - i] != '0' || bo  )
				bo = 1;
			else
				move++;
			if(bo )
			s[k++] = num[len - 1 - i] -'0';
		}
				len =  k;

	return * this;

}


begin begin::operator +(const begin & b) {
	
	begin c;
	c.len = 0;
	int l = (len > b.len) ? len : b.len, i, a = 0;
	for (i = 0; i < l || a; i++) {
			
		a = a + s[i] + b.s[i];
		c.s[i] = a % 10;
		a = a / 10;
	}
	c.len = i;
	return c;
}

begin begin::operator +=(const begin & b) {

	*this = * this + b;
	return * this;
}



begin begin::operator *(const begin & b) {
	
	begin c;
	c.len = 0;
	begin sum;
	sum.len = 0;
	int i, j, k, a = 0;
	for (i = 0; i < b.len; i++) {

		for (k = i, j = 0; j < len || a; j++, k++) {
			
			a = a + s[j] * b.s[i]; 
			c.s[k] = a % 10 ;
			a = a / 10 ;
			
		}
		c.len = j + i;
		sum += c;
		memset(c.s, 0, sizeof(c.s));
	}
	
	return sum;
}

void manage () {

	int i, count = 0;
	for (i = 0; i < strlen(s); i++) {
			
			if(count == strlen(s) - dection  || i != count)
				break;
			if(s[i] == '0')
				count++;
		
	}

	for(i = 0 ; i < strlen(s)- count; i++)
		s[i] = s[i + count];
	s[i] = '\0';


}

int main() {

		int i, j;

		while(scanf("%s%s", s, s1) != EOF) {
				dection = 0;
			s[6]='\0';

			//找到小数点位置并移除小数点
			for(i = 0; i < strlen(s); i++) {
			
				if(s[i] == '.') {
					dection = strlen(s) - 1 - i;
					for(j = i; j < strlen(s); j++) {

							s[j] = s[j + 1];
					}
			
					break;
				}
				 
			}
			//去掉前导0
				manage();
				
				sscanf(s1, "%d", &j);
				a = s;
				ans = s;
				dection -= move;
				for (i = 0; i < j - 1; i++) {
					
					sum = a * ans;
					a = sum;
					memset(sum.s, 0, sizeof(sum.s));
				}

				dection *= j;
				
				if(dection >= a.len )
					printf(".");

				if(dection > a.len)
					for(i = 0; i < dection - a.len; i++)
						printf("0");

				for(i = a.len - 1; i >=0; i--) {
				
					printf("%d", a.s[i]); 
					if(i ==  dection && dection)
						printf(".");
				}
				printf("\n"); 
				memset(a.s, 0, sizeof(a.s));
				memset(sum.s, 0, sizeof(sum.s));
				memset(ans.s, 0, sizeof(ans.s));
				
		}
	return 0;
}


你可能感兴趣的:(748 - Exponentiation)