0

I need to write a program that will calculate the arithmetic and geometric average of 10 variables. When I run tests on the program, it fails to calculate the geometric mean when there are numbers that include zero, for instance the series: 3 2 1 0 0 0 2 1 1 8; The output should be 1.9195

*(when all the variables are 0, the output should be that there is no answer, but when there are zeros in addition to other numbers- it should exclude them and calculate only the natural numbers)

#include <stdio.h>
#include <math.h>
void main()
{
    int num, i;
    float sum, mult;

    printf("Enter 10 variables: ");

    sum = 0;
    mult = 1;

    for (i=0; i<10; i++)
    {
        scanf("%d", &num);
        sum += num;
        mult *= num;
    }

    if (mult == 0 || mult < 0)
    {
        printf("No positive numbers, hence no geometric mean"); 
    }
    else 
    {
    printf(" %.4f", pow(mult, (1.0 / i)));
    }

    printf(" %.4f", sum / i);
}  
  • 1
    Perhaps the problem is the multiplication with `0`? Try to add a check and if `num == 0` then don't do the multiplication? – Some programmer dude Dec 02 '19 at 09:40
  • 3
    The geometric mean of these number is `0`. If you want to exclude zeros, then you must do so before multiplying them to `mult`. – walnut Dec 02 '19 at 09:40
  • 1
    This isn't a C problem, but one of definition, although you are using C. Three workarounds are given [here](https://www.wwdmag.com/channel/casestudies/handling-zeros-geometric-mean-calculation). – Weather Vane Dec 02 '19 at 09:41
  • 2
    The geometric mean of given numbers is zero, since it contains zero.If you want to exclude zeros before calculating geometric means add a condition check before multiplication and change the parameter of pow() accordingly. – Gopika BG Dec 02 '19 at 09:47
  • 1
    Note that `mult` being negative or zero does not imply that there were no positive inputs, and `mult` being positive does not imply that all inputs were positive. (You need to check the sign as you go, not after the fact.) – molbdnilo Dec 02 '19 at 09:55
  • In addition to skipping multiplication by zero, you also need to count the non-zero elements. If the count is zero you can output the message saying there is no geometric mean. Otherwise, the geometric mean is `pow(mult, 1.0 / count)`. – Ian Abbott Dec 02 '19 at 10:11
  • You need another variable to count the non-0 values, which according to the edit, should be skipped. Since there are 7 non-0 values, that gives the 7th root, not the 10th, and the product is 96. The 7th root of 96 is 1.91947... – Weather Vane Dec 02 '19 at 10:11
  • @Veronika Kovaleva: Curious, why use `float` instead of `double`? – chux - Reinstate Monica Dec 02 '19 at 11:50

1 Answers1

0
mult *= num;

here you are multiplying with 0, you will get only zero output. add a condition to multiply if number is not zero,.

thomachan
  • 378
  • 3
  • 14