(java保留n位小数)precise math function 北京信息科技大学第十届ACM程序设计竞赛 第2题

precise math function

Time Limit : 3000/1000ms (Java/Other)   Memory Limit : 65535/32768K (Java/Other)

Total Submission(s) : 2   Accepted Submission(s) : 2

Font: Times New Roman | Verdana | Georgia

Font Size: ←→

Problem Description

 

喜爱ACM的PBY同学遇到了一道数学难题,已知底数n,请你帮他准确的计算出结果a = n^π(n的π次方),结果保留小数点后x位。

Input

第一行是一个整数t,表示测试实例的个数;

然后是t行输入数据,每行包含两个正整数n和x,表示底数和保留位数。

1 <= t <= 100,1 <= n <= 500,1 <= x <= 6)

Output

对于每组输入数据,分别输出结果a,每个输出占一行。

Sample Input

31 37 69 1

Sample Output

1.000451.807873995.0

Author

bistuacm

Statistic | Submit | Back

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int t = in.nextInt();
        while(t-->0) {
            int n = in.nextInt();
            int x = in.nextInt();
            double m = Math.pow(n, Math.PI);
            BigDecimal m1 = new BigDecimal(m);
            double b1 = m1.setScale(x, BigDecimal.ROUND_HALF_UP).doubleValue();//四舍五入保留x位小数,但是注意小数最后的非0的数的后面可能会被舍掉。
            System.out.println(roundByScale(b1,x));
        }
    }
//补0
    public static String roundByScale(double v, int scale) {   
        String formatStr = "0.";  
        for(int i=0;i<scale;i++){  
            formatStr = formatStr + "0";  
        }  
        return new DecimalFormat(formatStr).format(v);  
    }  
}

猜你喜欢

转载自www.cnblogs.com/Weixu-Liu/p/9165573.html