Reputation: 1
I have no idea what went wrong, but I keep getting the wrong result, which is the value of the count is not correct.
import java.util.Scanner;
public class Learn
{
public static void main (String args[])
{
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.println("Enter the number of items: ");
int n = input.nextInt();
double[] numbers = new double[n];
double sum = 0;
System.out.println("Enter all the numbers");
for(int i=0; i < n; i++)
{
numbers[i] = input.nextDouble();
sum += numbers[i];
}
double average = sum/n;
int count = 0;
for(int i =0; i <n; i++)
{
if(numbers[i]>average);
count++;
}
System.out.println("Average is " + average);
System.out.println("Number of elements above the average is " + count);
}
}
But with this program, it looks exactly the same as the above one, it will work correctly. I really think these two programs are identical but why there is a different result here.
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.println("Enter the number of items");
int n = input.nextInt();
double[] numbers = new double[n];
double sum = 0;
System.out.println("Enter the numbers: ");
for(int i=0; i < n; i++)
{
numbers[i] = input.nextDouble();
sum += numbers[i];
}
double average = sum/n;
int count = 0;
for(int i =0; i <n;i++)
{
if(numbers[i] > average)
count++;
}
System.out.println("Average is " + average);
System.out.println("Number of elements above the average is " + count);
Upvotes: 0
Views: 31
Reputation: 437
Pay attention to this line:
for(int i =0; i <n; i++)
{
**if(numbers[i]>average);**
count++;
}
you must remove the ;
from the end of the if command to increase the count if the condition is true.
If you dont change it, the code increase the count anyway, even if numbers[i]<=average
Upvotes: 1