sean_g_b
sean_g_b

Reputation: 55

My 'if' statement is not working properly

I have an assignment where I am supposed to determine whether the average of three values is 'above average' or 'below average'. For some reason whatever is input will always be above average as the result. Here is my code below, thank you for any help!

import java.util.Scanner;

class Lesson_12_Activity_One {
    public static void main(String[] args)
    {
        Scanner scan = new Scanner(System.in);

        System.out.println("Enter three values");
        double x = scan.nextDouble();
        double y = scan.nextDouble();
        double z = scan.nextDouble();
        double t = (double)Math.round(100*((x+y+z)/3));

        System.out.print("The average is " + (t/100));

        if(t >= 89.5)     
            System.out.print(" ABOVE AVERAGE");
        else
            System.out.print(" BELOW AVERAGE");    
    }
}

Upvotes: 1

Views: 72

Answers (3)

Daniël van den Berg
Daniël van den Berg

Reputation: 2355

I'm gonna guess that you're mixing up perunages and percentages. That means, at one point in your program you use 0.5 and in the other 50, both as 50%.

    double t = (double)Math.round(100*((x+y+z)/3));

    System.out.print("The average is " + (t/100));

With x, y and z all as 50, this will output 50. t = 100 * (50 + 50 + 50)/3 = 5000, the output is (t/100) = 50.

if(t >= 89.5) however tests with t = 5000. To solve this, go down one of two paths.

  1. Replace all percentages for perunages. This means inputting numbers from 0 to 1. To do this, do the following:
    change your t-initialization for double t = (double)Math.round(1000*((x+y+z)/3)) / 1000 This will make T be in between 0 and 1 with 3 digits precision.
    Replace your if with if (t >= 0.895)

  2. Replace all perunages with percentages. This means inputting numbers from 0 to 100.
    To do this, remove the 100* from your double t = (double)Math.round(100*((x+y+z)/3));, and the /100 from the output message.

Upvotes: 0

AbtPst
AbtPst

Reputation: 8008

if(t/100 >= 89.5)     
   System.out.print(" ABOVE AVERAGE");
 else
   System.out.print(" BELOW AVERAGE"); 

by the way why are you multiplying and then dividing by 100?

Upvotes: 0

Eran
Eran

Reputation: 393771

The average is t/100 but in your condition you test if t > 89.5 (which is always true since t is the average multiplied by 100).

Just remove both the multiplication by 100 and the division by 100. They don't seem necessary.

double t = Math.round((x+y+z)/3);

System.out.print("The average is " + t);

if(t >= 89.5)     
    System.out.print(" ABOVE AVERAGE");
else
    System.out.print(" BELOW AVERAGE");    
}

Upvotes: 2

Related Questions