Q - 高精度(大数)n次方(POJ 1001)

题目链接

题解

1.将输入的字符串转化化成整型存储在number 中,运算时每次乘以number

2.将输入的字符串逆向存储在整型数组a[]中,用于存储每次乘以number后的结果

3.具体运算过程就是求number的n次方,每次运算以a[]中的每一位数字乘上number

4.用point计算小数的位数,输出时逆序输出a[],并且处理小数个数即可

Code

#include <stdio.h>
#include <string.h>
const int N = 200;
 
int main() {
	char num[6]; //存放输入字符串 
	long number; //将输入的字符串转为不带小数点的整数 
	int n,point,count;  
	int a[N]; //存储运算结果
	while (scanf("%s%d", num, &n) == 2) {
		number = 0; point = -1; count = 0;
		
		//输入设置 
		int note1,note2; //去除字符串前面和后面多余的0 
		for (int i = 0; i <= 5; i++) {
			if (num[i] != '0') {
				note1 = i;
				break;
			} 		
		}	
		for (int i = 5; i >= 0; i--) {
			if (num[i] != '0') {
				note2 = i;
				break;
			} 		
		}
		for (int i = note1; i <= note2; i++) {
			if (num[i] != '.') {
				number = number*10 + (num[i]-48);
			}
		}
		for (int i = note2; i >= note1; i--) {
			if (num[i] != '.') {
				a[count++] = num[i]-48;		
			}
		}
		for (int i = note1; i <= note2; i++) {
			if (num[i] == '.') {
				point = (note2-i)*n;
				break;
			}
		}
 
		//运算 
		long s,d;
		for (int k = 1; k < n; k++) {
			d = 0;
			for (int i = 0; i < count; i++) {
				s = a[i]*number+d;	
				a[i] = s%10;
				d = s/10;
			}
			while (d != 0) {
				a[count++] = d % 10;
				d /= 10;
			}
		}
		
		//输出设置	
		bool flag = true;
		if (count < point) {  
			flag = false;
			printf(".");
			while (point != count) {
				point--;
				printf("0");
			}
		}
		for (int i = count-1; i >= 0; i--) {
			if (flag == true && i == point-1) printf(".");
			printf("%d", a[i]);
		}
		printf("\n");
	}
	return 0;
}
上一篇:flask note1


下一篇:Linux - Shell - diff