Simple equation of division in java

Asked

Viewed 2,015 times

3

Good afternoon, I am beginner in java and need to do the following calculation in the language

For example: (8/7) *100 = 114%

(4/7)*100 = 57,14%

(90/112)*100 = 80,35%

But the way I’m developing it does not return me the correct result

  double total = (90/112) * 100 ;
  System.out.println(total);

and it returns me 0.0 on the console

how would I make him return me the real result?

2 answers

8

( 90 / 112 ) is a division of integers.

Java makes the cast for double that shoots down (0) due to the result: 0.8035... when multiplication is done: 0 x 100 = 0.

You can cast at least one of the operators to get the desired result:

double total = ((double) 90 / 112) * 100;
System.out.println(total); // 80.35714285714286

Other ways to cast:

double total = (90d / 112) * 100;
double total = (90.0 / 112) * 100;

3

There are two ways to solve this:

double total = (90/112d) * 100 ;
System.out.println(total);

Or:

double total = (90./112.) * 100 ;
System.out.println(total);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.