OhHeyImBri
OhHeyImBri

Reputation: 23

Java calculation method is returning 1.0 instead of 0.5? What do?

When testing this code with Max 70 and Min 59 it returns 1.0 instead of 0.5. Is my formula wrong? Also the 2nd if statement is for these directions: (public static double hdd(int max, int min) that returns the HDD for a single day. If either max or min is -999 (missing) return 0.0. If max < min return 0.0.) So idk if relevant to the problem.

/**
 * Calculate heating degree day.
 * @param max The highest temperature for a given day.
 * @param min The lowest temperature for a given day.
 * @return heating degree day data for this day.
 */
public static double hdd(int max, int min)
{
    double average = (max + min) / 2;
    double hdd = 0.0;

    if (average < 65.0)
    {
        hdd = 65.0 - average;
    }
    else
    {
        hdd = 0.0;
    }

    if(max == -999 || min == -999)
    {
        hdd = 0.0;
    }
    else if (max < min)
    {
       hdd = 0.0;   
    }


    return hdd;

Upvotes: 0

Views: 734

Answers (2)

chathux
chathux

Reputation: 831

when you divide an integer by another integer the result will be also an integer. so it will not have a fractional part.

you can fix this by changing this line

double average = (max + min) / 2;

to this

double average = (max + min) / 2.0;

Upvotes: 1

Dawood ibn Kareem
Dawood ibn Kareem

Reputation: 79807

Your issue is that (max + min) / 2 is an integer division, which means it gets truncated to the integer below. In this case, (70 + 59) / 2 gives 64, which you are then storing in a double. But that won't restore the missing 0.5.

You need to convert either the numerator or the denominator to a double before dividing. Writing 2.0 in place of 2 is one way to achieve this.

Upvotes: 2

Related Questions