简体   繁体   English

Java-如何快速转换变量整数->浮点数?

[英]Java - how to quickly convert variable integer -> float?

I am newbie in Java and just trying to convert a variable according to math operation. 我是Java的新手,只是想根据数学运算转换变量。 Let's have following scheme: 让我们有以下方案:

int var_result;
if(addition) {
  var_result = number1+number2; // number1, number2 => integers
}
else if(division){
  var_result = (float) number1 / number2;
  // and here is the problem - I don't know, how to convert "var_result" from integer to float
}

...just print var result ...

Is there any quick way, how to convert the var_result variable in this case? 有什么快速的方法,在这种情况下如何转换var_result变量? The easiest way in this example would be don't convert it and just use float var_result_float , but I don't want to solve it this way... 在此示例中,最简单的方法是不进行转换,而仅使用float var_result_float ,但我不想以这种方式解决它...

Thanks 谢谢

int var_result; is already declared. 已经声明。 You can't expect to store a float in it, without losing precision. 您不能期望在其中存储浮点数而不损失精度。

When you perform type-casting, the variable is temporarily treated as another type for the purpose of evaluation of an expression but that does not change what it actually is. 当执行类型转换时,出于评估表达式的目的,该变量会暂时被视为另一种类型,但不会改变其实际含义。

An int remains an int. 一个整数仍然是一个整数。 You should go with float var_result_float to store a float. 您应该使用float var_result_float来存储浮点数。

int var_result is an int variable. int var_result是一个int变量。
If you need a float use a float var_result 如果需要float使用float var_result

I don't want to solve it this way... 我不想这样解决...

Well...This is the only way. 好吧...这是唯一的方法。

If you need to store an int or float in a variable you can use a double to store all possible values. 如果需要将intfloat存储在变量中,则可以使用double来存储所有可能的值。

IMHO Don't use a float if you can possibly avoid it as its precision is fairly poor. 恕我直言,如果可以避免使用float则不要使用它,因为它的精度相当差。

You can't change type of variable, but you can get what you want this way: 您无法更改变量的类型,但是可以通过以下方式获得所需的内容:

Object var_result; 
if(addition) { 
  var_result = new Integer(number1+number2); // number1, number2 => integers 
} 
else if(division){ 
  var_result = new Float( (float) number1 /  (float) number2); 
} 

Of course to use the number, you have to test the type with instanceof and do cast to Float or Integer as needed, so this is very clumsy. 当然要使用数字,您必须使用instanceof测试类型并根据需要将其强制转换为Float或Integer,因此这非常笨拙。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM