fork download
  1. int main () {
  2. /* variable definition: */
  3. int count;
  4. double avg, value, weight, sum, sumw;
  5. /* Initialize */
  6. count = 0;
  7. sum = 0;
  8. sumw = 0;
  9. avg = 0.0;
  10. // Loop through to input values
  11. while (count < 5) {
  12. printf("Enter a value and its weight: ");
  13. // use %lf for double, %f for float
  14. scanf("%lf %lf", &value, &weight);
  15. if (weight >= 0) {
  16. sumw = sumw + weight;
  17. sum = sum + value * weight;
  18. count = count + 1;
  19. }
  20. else {
  21. printf("Weight must be positive\n");
  22. } // end if weight ok
  23. } // end reading input values and weights
  24. // Calculate avg if sumw is not 0
  25. avg = sum / sumw;
  26. printf("average is %lf\n " , avg );
  27. return 0;
  28. } // end main
Success #stdin #stdout 0s 4496KB
stdin
2 1 2  1 -1
stdout
Enter a value and its weight: Enter a value and its weight: Enter a value and its weight: Enter a value and its weight: Enter a value and its weight: average is 0.200000