[英]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.