-1

I'm new to Java.

If you want to know what I'm trying to solve, check this: http://codeforces.com/problemset/problem/200/B

The two versions of the code, solve the same problem:

1-(for loop) version

public static void method() {
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    double sum = 0;
    for (int i = 0; i < n; i++)
        sum += (sc.nextInt() / 100.0);

    System.out.println(sum * 100.0 / n);
}

2-(while loop) version

    public static void method() {
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    double sum = 0;

    while (n-- > 0) {
        sum += (sc.nextInt() / 100.0);
    }
    System.out.println((sum * 100.0) / n);
}

===================================================

Here is the input for each of them:

3

50 50 100

Here is the output of each of them:

1-(for loop): 66.66666666666667

2-(while loop): -200.0

===================================================

Why the output differs?

2 Answers2

1

n-- this will change the value of n and it will make it -1 at end. so your sum will devide by -1 and you get -200 but in first solution n does not change and at end 200/3 = 66.6

Mohsen
  • 4,536
  • 2
  • 27
  • 49
0

it looks like you are decrementing n and then evaluating which will allow n to become negative

-- X = decrement X then evaluate 


X -- = evaluate X then decrement X
Totalattak
  • 24
  • 5