简体   繁体   中英

Calculating average of two numbers is returning 0.0(Java)

After creating a simple java craps game, I decided to have it test for 1 million iterations. For whatever reason, dividing the two numbers with this code

System.out.println("Wins: "+w+" Losses: "+l);
double avg = 100*(w / l);
System.out.println("Average: "+avg);

This for whatever reason prints the correct number of wins and losses but when it divides it just gets 0.0 Any help would be much appreciated.

Resolved code:

    double w = 0 , l = 0;
    for(int c=1;c<1000000;c++)
    {
    if(playGame() == true)
    {
        System.out.println("You win!");
        w++;
    }
    else
    {
        System.out.println("You lost!");
        l++;
    }
    }
    System.out.println("Wins: "+w+" Losses: "+l);
    double avg = (100*(w / l))/2;
    System.out.println("Average: "+avg);

i suspect that your w and l might be ints. when you divide ints, they don't evaluate to doubles, they evaluate to ints, and they always round down

Now you have 2 options if that indeed is the case

  • take w and l as doubles during input
  • cast w and l to doubles before you don any arithmetic on them.

try:

double dWin = w;
double dLoss = l

System.out.println("Wins: "+dWin+" Losses: "+dLoss);
double avg = 100*(dWin / l);
System.out.println("Average: "+avg);

Assuming that w and l are ints your doing integer math. Unless the numerator is larger than the denominator, integer division will return zero.

If your inputs are ints then your output will be ints. One or both of your inputs have to be floats or doubles.

If they are ints and you cannot change them to float you can do

double avg = 100*(w / (l * 1d));

which will make la double so that the result is a double.

without the *100d you are putting an int value inside a double.

The results of operations is of the biggest operands type ... so if you apply / operation on two int the answer will be int .

if you want average with a precision you should typecast one of the operands into double.

Try writing

double avg = 100*(((double)w) / l);

Everyone else is forgetting the associative rules of multiplication and division

double avg = 100.0 * w / l;

Will give you the right answer and avoid the ugly looking cast :-)

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