Problem: Read several (at least one) non-negative integers and computer their real average.
/ /Establish an ``accumulator''
int sum = 0;
/ /Establish a counter to count data.
int count = 0;
/ /Sum the integers
int num = IO.read_int ();
while (num
> =
0)
{
sum = sum + num;
count = count + 1; / /count + +
num = IO.read_int ();
}
/ /Compute and display average.
double ave = (double) sum
/
(double) count;
IO.println (``ave = ''
+
ave);
} / /end
In this program, the input of 5, 10, - 2 would result in an output of 7.5. The input of - 2 broke the loop of the while statment and resulted in the input of 5 and 10 being averaged.
|