public static void main(String[] args) {
float f1 = 1234.5678f
int f2 = 99900
String f3 = String.format("x=%.2f, y=%.3f", 100.22222f, 200.33333f)
String f4 = String.format("x=%.4f, y=%.5f", 100.22222f, 200.33333f)
System.out.printf("f1 = %.2f\n", f1)
System.out.printf("f2 = %.2f\n", (float)f2)
System.out.printf("f3 = \"%s\"\n", f3)
System.out.printf("f4 = \"%s\"\n", f4)
}
}
输出:
f1 = 1234.57
f2 = 99900.00
f3 = "x=100.22, y=200.333"
f4 = "x=100.2222, y=200.33333"
总的说来,我用了两中方式。System.out.printf("f(%d)= %.2f\n",x,y)printf是java继承C来的,可以用c的方式来格式化输出。
还有就是java自己提供了更为丰富的格式化输出。用到Format,format 是一个用于格式化语言环境敏感的信息(如日期、消息和数字)的抽象基类。 Format 定义了编程接口,用于将语言环境敏感的对象格式化为 String(使用 format 方法)和将 String 重新解析为对象(使用 parseObject 方法)。数字
NumberFormat 用于格式化输出 数字,在java.text.包中,如果你有API,那就很简单的多了。
你复制下去,运行一下,我测试的是
3
2 =0.5
3 =0.33
4 =0.25
和你的要求一样。希望采纳。
import java.text.NumberFormat
import java.util.Scanner
public class Test
{
public static void main(String args[])
{
int repeat, ri,x
double y
Scanner in=new Scanner(System.in)
repeat=in.nextInt()
NumberFormat f=NumberFormat.getInstance()
f.setMaximumFractionDigits(2)
for(ri = 1ri <= repeatri++)
{
x=in.nextInt()
/*---------*/
if(x!=0)
y=1.0/x //还有在这里,是1.0/x,不然结果全是0.如果不懂,下面有连接,我回答的
else
y=0
//System.out.println("f("+x+")="+y)
String s=f.format(y)
//System.out.printf("f(%d)= %.2f\n",x,y)
System.out.println("f("+x+")="+s)
//如果要得到你所说的,我建议用numberformat来格式化输出。
}
}
}
http://zhidao.baidu.com/question/390739373.html?old=1&afterAnswer=1#here
System.out.println(Double.parseDouble(new
DecimalFormat("#.##").format(a))+ " " +
Double.parseDouble(new DecimalFormat("#.##").format(b)))
把输出语句换成这个就行了。
若出现这种问题,import java.text.DecimalFormat
你没导这个包,导入就可以了。