I want to write a program that reads a set of values, entered by the user. Then I want to print the smallest, largest, sum and average of the values. See below:
float largest = in.nextFloat();
float smallest = largest;
while (inputs != -1) \\-1 is the sentinel
{
inputs = in.nextFloat();
if (inputs !=-1)
{
sum = sum + inputs;
counter++;
if (inputs > largest)
{
largest = inputs;
}
if (inputs < smallest)
{
smallest = inputs;
}
}
}
This doesn't work. What happens is that for the sum, the first input doesn't get counted. So for example the set 1 2 3 4 5 -1 would give a sum of 14 instead of 15 (keep in mind -1 is the sentinel). I suspect I know why this is, because the first value entered by the user will be used to initialise "float largest" and then the second value will be the first one to go into "inputs".
However even though I suspect I know the mistake, I have no idea how to fix it. I tried moving the first two lines of code into the while loop but that gives a lot of errors which lead nowhere. Any idea how to do this?