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);
}
}

最低0.47元/天 解锁文章
5336

被折叠的 条评论
为什么被折叠?



