gpt4 book ai didi

java: 如何使用 printf 打印美元符号和带有 2 位小数的 double ?

转载 作者:行者123 更新时间:2023-11-30 07:00:25 24 4
gpt4 key购买 nike

我对 printf 真的很不好。如何将 %$.2f 添加到我的字符串格式中,以便我可以获得如下所示的干净内容:(我之前忘记添加“$”)

MP3 Player cost:                        $580.39
Smart Phone cost: $510.93
Digital Watch cost: $495.99
Tablet cost: $643.17
Portable Gaming System cost: $485.17



import java.util.Scanner;

public class test2 {

public static void main(String[] arg) {

Scanner in = new Scanner(System.in);

int [][] matrix = { // 5 rows, 7 cols
{ 9, 13, 4, 7, 1, 14, 10},
{ 8, 2, 12, 11, 6, 15, 2},
{ 9, 6, 7, 10, 15, 8, 3},
{ 12, 14, 8, 15 ,2 , 7, 8},
{ 12, 10, 3, 11, 8, 3, 5},
};

String [] product = new String [5];
product [0] = "MP3 Player";
product [1] = "Smart Phone";
product [2] = "Digital Watch";
product [3] = "Tablet";
product [4] ="Portable Gaming System";

double [] price = {10.75, 15.27, 5.98, 9.67, 4.32, 12.50, 1.42}; // 7 elements

costOfEach(matrix, product, price);
}

// compute and display the cost of manufacturing each device
public static double costOfEach(int matrix[][], String[] product, double price [] ){
double cost = 0.00;
String item = "";
double maxCost = 0.00;
double minCost = Double.MAX_VALUE;
int maxCostIndex = 0;
int minCostIndex = 0;

就在这里。我尝试了很多组合但没有结果

        String format = "%-40s%s%n"; 
for (int row = 0; row < matrix.length; row++){
cost = 0;
for (int col = 0, i = 0; col < matrix[0].length && i < price.length; col++, i++){

cost += matrix[row][col] * price [i];
}

System.out.printf(format, product[row] + " cost: $%.2f", cost);
}
return cost;
}

}

最佳答案

上面的答案是正确的,要添加 $ 符号只需编辑以下行:

String format = "%-40s$%.2f%n";

你的输出:

MP3 Player cost:                        $580,39
Smart Phone cost: $510,93
Digital Watch cost: $495,99
Tablet cost: $643,17
Portable Gaming System cost: $485,17

关于java: 如何使用 printf 打印美元符号和带有 2 位小数的 double ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41027473/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com