1001 . Exponentiation

来源:互联网 发布:免费网络教育平台 编辑:程序博客网 时间:2024/05/12 07:10


Problems involving the computation(估计,计算) of exact values of very large magnitude(大小,量极) and precision are common. For example, the computation of the national debt(国债) is a taxing experience for many computer systems. 

This problem requires that you write a program to compute the exact value of Rn where R is a real number ( 0.0 < R < 99.999 ) and n is an integer such that 0 < n <= 25. 


The input will consist of a set of pairs of values for R and n. The R value will occupy columns 1 through 6, and the n value will be in columns 8 and 9.


The output will consist of one line for each line of input giving the exact value of R^n. Leading zeros(前导0) should be suppressed in the output. Insignificant(无关紧要的) trailing zeros(后补0) must not be printed. Don't print the decimal point(小数点) if the result is an integer.

Java.
//java 自带BigDecimal很方便。但需string类处理。import java.math.BigDecimal;import java.io.*;import java.text.DecimalFormat.*;import java.util.*;public class Main{public static void main(String args[]){Scanner cin = new Scanner(System.in);while(cin.hasNext()){String a = cin.next();int b = cin.nextInt();BigDecimal f = new BigDecimal(a);BigDecimal g = new BigDecimal("1");for(int i =1 ;i <= b; i++){g = g.multiply(f);}BigDecimal y = new BigDecimal(0);if(g.compareTo(y) == 0)System.out.println("0");  //等于0时else {String result;result = g.toPlainString();int pos;int is = 1;pos = result.lastIndexOf(".");  for(int i = pos-1 ;i >= 0 ; i--)//前导零的处理{if(result.charAt(i) !='0')is = 0;}if(is == 1)//需要切割{result = result.substring(pos,result.length());}is = -1;pos = result.lastIndexOf(".");if(result.charAt(result.length()-1) == '0')for(int i = result.length()-1;i > pos; i--){if(result.charAt(i) == '0'){is = i;}else break;}if(is != -1)if(is != pos + 1)result = result.substring(0,is);else result = result.substring(0,is-1);System.out.println(result);}//String result = g.toPlainString();}}}//hasNext()是Scanner类的一个方法,判断是否有输入,有输入项,a .hasNext()为true,没有输入项,a .hasNext()为false//compareTo比较此对象与指定对象的顺序。字典序。如果该对象小于、等于或大于指定对象,则分别返回负整数-1、零0或正整数1//toPlainString():返回不带指数字段的此 BigDecimal 的字符串表示形式//int lastIndexOf(int ch): 返回此字符串指定字符最后一次出现







0 0
原创粉丝点击