Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is my calculation not working in Java?

I tried debugging but the variable y remains as 0 instead of carrying out the expected calculation. Someone tell me what I’m doing wrong. Thank you.

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Scanner scan = new Scanner(System.in);
    System.out.println("Enter odd number: ");
    int n = Integer.valueOf(scan.nextLine());
    scan.close();
    double y = 0;
    for (int x = 1; x < n + 1; x = x + 2) {
        y += (x/(x + 1));
    }
    System.out.println("Y = " + y); 
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Problem is with the (x/(x + 1)). Variable x is of data type integer. This will also result in an integer when dividing. Integers are whole numbers and are simply cut to 0 at 0.x for this reason.

To fix this have a look here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading