-1
什么是写这样的事情最好的办法:打印传单N浮动小数或双
Scanner input = new Scanner(System.in);
int n = input.nextInt();
double d = 5.123456789123456789;
System.out.printf("%.nf", d);
谢谢!
什么是写这样的事情最好的办法:打印传单N浮动小数或双
Scanner input = new Scanner(System.in);
int n = input.nextInt();
double d = 5.123456789123456789;
System.out.printf("%.nf", d);
谢谢!
格式字符串只是您可以在运行时创建的String
。例如。
System.out.printf("%." + n + "f", d);
要保留double的小数位数,可以使用java DecimalFormat。
由于只有在运行时才知道小数位数,所以您还需要在运行时为DecimalFormat生成模式。
所以:
int n = 5; // or read in from user input
String decimalFormatPattern = ".";
for (int i =0 ; i < n; ++i) { // generate pattern at runtime
decimalFormatPattern += "#";
}
// format pattern would be .#####
DecimalFormat decimalFormat = new DecimalFormat(decimalFormatPattern);
double d = 5.123456789123456789;
System.out.println(decimalFormat.format(d));
你想要做什么?你想打印双倍n次? –
查看NumberFormat和DecimalFormat – ControlAltDel