如何使用整数作为输入并打印未舍入的百分比

How to use intergers as input and print an unrounded percentage

我写了一个程序,我想在其中获取一定数量的片段(输入数据)并显示相对于输入的百分比。问题是,如果我使用 int 作为数据输入,我会得到四舍五入的结果。我可以使用 double,但我不希望程序接受小数,所以只接受真正的整数。

简而言之我想要: * 输出应该是 56.34% * 输入只能是5、3等数字

//Number of available tiles
static final int AVAILABLE_TILES = 64;

//Number of white pieces
out.printf("Enter the number of white pieces on the board: ");
//Input of white pieces
double whitePiecesOnBoard = in.nextDouble();

//Number of black pieces
out.printf("Enter the number of black pieces on the board: ");
//Input of black pieces
double blackPiecesOnBoard = in.nextDouble();

//Total number of pieces
double totalPieces = whitePiecesOnBoard + blackPiecesOnBoard;

//Percentage of black pieces of all pieces
double blackPiecesPercentagePieces = (blackPiecesOnBoard*100)/totalPieces;

//Percentage of black pieces of available tiles
double blackPiecesPercentageTiles = (blackPiecesOnBoard*100)/AVAILABLE_TILES;

out.printf("Black pieces %.2f%% and other pieces %.2f%%", blackPiecesPercentagePieces, blackPiecesPercentageTiles);

在计算百分比时将您的参数之一投射到 double。这可以通过 (double) 显式完成,也可以通过使 100 成为 100.0:

来隐式完成
//Percentage of black pieces of all pieces
double blackPiecesPercentagePieces = (blackPiecesOnBoard*100.0)/totalPieces;

//Percentage of black pieces of available tiles
double blackPiecesPercentageTiles = (blackPiecesOnBoard*100.0)/AVAILABLE_TILES;