Java字符串与格式化输出应用

389、编写一个程序,测试在不同大小的字段中打印整数值 12345 和浮点数值 1.2345 的结果。

以下是将给定文本内容转换为 Markdown 格式的结果:

以下是一个 Java 程序示例,用于测试在不同大小的字段中打印整数值 `12345` 和浮点数值 `1.2345` 的结果:

```java
public class FieldSizeTest {
    public static void main(String[] args) {
        int integerValue = 12345;
        double floatingValue = 1.2345;
        // 测试不同字段大小打印整数值
        System.out.println("测试不同字段大小打印整数值:");
        System.out.printf("字段大小为 5: %5d\n", integerValue);
        System.out.printf("字段大小为 8: %8d\n", integerValue);
        System.out.printf("字段大小为 10: %10d\n", integerValue);
        // 测试不同字段大小打印浮点数值
        System.out.println("\n测试不同字段大小打印浮点数值:");
        System.out.printf("字段大小为 5: %5.4f\n", floatingValue);
        System.out.printf("字段大小为 8: %8.4f\n", floatingValue);
        System.out.printf("字段大小为 10: %10.4f\n", floatingValue);
    }
}

这个程序定义了一个整数值 12345 和一个浮点数值 1.2345 ,然后使用 printf 方法在不同大小的字段中打印它们。对于整数,直接使用 %[字段大小]d 格式化;对于浮点数,使用 %[字段大小].[小数位数]f 格式化。


##390、编写一个程序,将数值 100.453627 分别四舍五入到最接近的整数、十分位、百分位、千分位和万分位,并打印输出。
以下是一个 Java 程序示例,用于将数值 100.453627 分别四舍五入到最接近的整数、十分位、百分位、千分位和万分位并打印输出:

```java
public class RoundingExample {
    public static void main(String[] args) {
        double num = 100.453627;
        // 四舍五入到最接近的整数
        int roundedToInteger = (int) Math.round(num);
        // 四舍五入到十分位
        double roundedToTenth = (double) Math.round(num * 10) / 10;
        // 四舍五入到百分位
        double roundedToHundredth = (double) Math.round(num * 100) / 100;
        // 四舍五入到千分位
        double roundedToThousandth = (double) Math.round(num * 1000) / 1000;
        // 四舍五入到万分位
        double roundedToTenThousandth = (double) Math.round(num * 10000) / 10000;
        System.out.println("四舍五入到最接近的整数: " + roundedToInteger);
        System.out.println("四舍五入到十分位: " + roundedToTenth);
        System.out.println("四舍五入到百分位: " + roundedToHundredth);
        System.out.println("四舍五入到千分位: " + roundedToThousandth);
        System.out.println("四舍五入到万分位: " + roundedToTenThousandth);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值