My code's while loop has two values in it, a weight and a value. my sentinel value is "-1". I have tried to modify the conditions in the while loop to everything I can think of but I'm at a loss. When I enter my sentinel value in my standard input, it ends the loop but also factors in the sentinel value in the average. below is the code:
Code:
<#include <stdio.h>
int main (void) {
/* variable definition: */
unsigned int counter;
int count;
double avg, value, weight, sum, sumw;
/* Initialize */
counter =0;
count = 0;
sum = 0;
sumw = 0;
avg = 0.0;
// Loop through to input values
while (value != -1)
{
printf("Enter a value and its weight, -1 to end: ");
// use %lf for double, %f for float
scanf("%lf %lf", &value, &weight);
printf("%.2lf (value) %.2lf (weight)\n", value, weight);
if (weight != 0) {
sumw = sumw + weight;
sum = sum + value * weight;
count = count + 1;
}
else {
printf("Weight must be positive\n");
} // end if weight ok
} // end reading input values and weights
// Calculate avg if sumw is not 0
avg = sum / sumw;
printf("average is %lf\n " , avg );
return 0;
} // end main>
and below is the output:
2 1 2 1 -1
stdout copy
Enter a value and its weight, -1 to end: 2.00 (value) 1.00 (weight)
Enter a value and its weight, -1 to end: 2.00 (value) 1.00 (weight)
Enter a value and its weight, -1 to end: -1.00 (value) 1.00 (weight)
average is 1.000000
I have tried to modify the code to read:
while (value && weight != -1)
While (value || weight != -1)
while (value, weight =! -1)
while (value != -1)
while (weight != -1)
While ((value) (weight) != -1)
while ((value), (weight) != -1)
none of these seem to work.