简体   繁体   中英

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?

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.

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.
So (45/100) should be cast to double as following:

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

45 is integer , 100 is an integer so 45/100 == 0

you can try using 45.0 and 100.0 instead

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. 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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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