简体   繁体   English

Java-Double和Int错误

[英]Java - Double and Int Error

I have a Variable like this 我有一个这样的变量

int tff = 100;
double x = (45/100) * tff;
int y = (int) (tff - x);
System.out.println(y);

It's should be output 55, but why the output is 100? 应该是输出55,但是为什么输出是100?

You need to identify the values as the specific number type that they represent. 您需要将值标识为它们代表的特定数字类型。 You can notice it at many examples. 您可以在许多示例中注意到它。 A simple number without an identifier as 100d or 100.0 for example will allways be handled as an integer. 一个没有标识符的简单数字,例如100d100.0 ,将始终被视为整数。

You could use the identifier for the type after the number like this. 您可以像这样在数字后面使用标识符。

int tff = 100;
double x = (45/100d) * tff;
int y = (int) (tff - x);
System.out.println(y);

Other examples where you could need this identifier could be the long. 您可能需要此标识符的其他示例可能很长。

// This wont compile since it is out of the integer range
long l = 12312354345346;
// This will compile since it is declared to be a long
long l = 12312354345346l;

(45/100) = 0.45 when (45/100) is double and (45/100) = 0 when (45/100) is integer. (45/100)为双精度时, (45/100)= 0.45 ;当(45/100)为整数时, (45/100)= 0
So (45/100) should be cast to double as following: 因此(45/100)应该转换为以下形式的两倍:

double x = ((double)45/(double)100)* tff;

45 is integer , 100 is an integer so 45/100 == 0 45integer100integer因此45/100 == 0

you can try using 45.0 and 100.0 instead 您可以尝试使用45.0100.0代替

int tff = 100;
double x = (45.0/100.0) * tff;
int y = (int) (tff - x);
System.out.println(y);

alternatively you could cast the numbers as doubles: 或者,您可以将数字转换为双精度:

double x = (((double)45)((double)/100)) * tff;

if you don't cast it to a double first. 如果您不先将其转换为两倍。 You will get a int out of it. 您将得到一个整数。 So your value wil be lower then '1', java thinks it is a zero. 因此,您的值将小于“ 1”,Java认为它是零。 so wat you have to do: 因此,您必须执行以下操作:

int tff = 100;
int value1 = 45;
int value2 = 100;
double x = ((double)value1 / (double)value2) * tff;
int y = (int)(tff - x);
System.out.println(y);

Output will be: 55! 输出将是:55!

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

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