[英]Java Convert double to int
我有此代碼,文本字段中的輸入為50,因此其輸出應為25,
但是有錯誤,因為沒有輸出
button_1.addActionListener(new ActionListener() {
String tfg = textField.getText().toString();
String tfc = textField.getText();
public void actionPerformed(ActionEvent e) {
if(textField.getText().toString().equals("0") ||
textField.getText().toString().equals("") ||
textField.getText().toString().equals(" ") ||
textField.getText().toString().matches("[a-zA-Z]+")) {
JOptionPane.showMessageDialog(Cow.this,
"Tree Amount Should Be 1 or More",
"Invalid Tree Amount",
JOptionPane.ERROR_MESSAGE);
}
if(!tfg.equals("0")) {
try {
int tfgg = Integer.parseInt(tfc);
int trcs = tfgg * 1;
double trcp = 1 / 2;
int trcc = (int) trcp * trcs;
System.out.println(new Integer(trcc).toString());
} catch (NumberFormatException se) {
}
}
}
});
我嘗試將我的php轉換為該代碼,這是我的php代碼:
$doorSeed = $mount * 1;
$doorPrice = 1 / 2;
$doorConvert = $doorPrice * $doorSeed;
echo "Treasure Chest Seed = ".$doorSeed." Price : ".$doorConvert." World Lock <br>";
int trcc = (int) trcp * trcs;
試試這個
int trcc = (int) (trcp * trcs);
您需要將complete expression
[ (trcp * trcs)
] (trcp * trcs)
而不只是將第一個變量trcp
為int
。 表達式trcs
的另一個變量為double
類型,因此表達式的結果變為double
。 這就是為什么要強制轉換完整的表達式。 所以你的最終結果將是int
int tfgg = Integer.parseInt(tfc.trim()); // tfc = 4; tfgg = 4;
int trcs = tfgg * 1; // trcs = 4 * 1 = 5;
double trcp = 1.0 / 2; // trcp = 0.5;
int trcc = (int) (trcp * trcs); // trcc = (0.5 * 5) = (2.5) = 2;
System.out.println(trcc); // 2;
double trcp = 1.0 / 2;
在這里,至少將一個值設為double
以便表達式將按@tunaki的建議計算為double
。
同樣,您的代碼中也不需要此語句int trcs = tfgg * 1;
。
像這樣使用:
String tfg ;
String tfc ;
public void actionPerformed(ActionEvent e) {
tfg = textField.getText();
tfc = textField.getText();
if(textField.getText().equals("0") || textField.getText().equals("") || textField.getText().equals(" ") || textField.getText().matches("[a-zA-Z]+")) {
JOptionPane.showMessageDialog(Cow.this,
"Tree Amount Should Be 1 or More",
"Invalid Tree Amount",
JOptionPane.ERROR_MESSAGE);
}
if(!tfg.equals("0")) {
try {
int tfgg = Integer.parseInt(tfc.trim()); // tfc = 4;
int trcs = tfgg; // trcs = 4 * 1 = 5
double trcp = 1.0 / 2; // trcp = 0.5
int trcc = (int) (trcp * trcs); // trcc = (0.5 * 5) = (2.5) = 2
System.out.println("HI: "+trcc);
} catch (NumberFormatException ignored) {
}
您的問題在這一行:
double trcp = 1 / 2;
這不會導致trcp = 0.5
而不會導致trcp = 0.0
,因為您正在對整數值進行除法(因此也將使用整數除法)。
您應該使用以下代碼:
double trcp = 1.0 / 2;
強制使用雙打進行划分。
其他的建議:
new Integer(trcc).toString()
應該替換為String.valueOf(trcc)
。 int trcs = tfgg * 1;
? 基本上,您有(int)0.5 = 0
。 在您的情況下, trcp = 0.5
且為double值,因此當將其trcp = 0.5
為整數時,結果為0。
當您執行(int)a + b
,此處帶括號的優先級運算為((int)a)+(b)
,因此您需要執行以下操作:
int trcc = (int) (trcp * trcs);
而不是以下內容:
int trcc = (int) trcp * trcs;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.