-2

I want to ask a question how to create a "Division" function which contains variable number of parameters in Java? Just Like As I did for sum method:

    public static int sum(int ... x)
    {
        int sum=0;
        for(int i : x)
        {
            sum=sum+i;
        }
        return sum;
    }
luk2302
  • 46,204
  • 19
  • 86
  • 119
  • 3
    well, what is that method supposed to do? why does the exactly same way not work for division? Are you running into integer division (https://stackoverflow.com/questions/4685450/why-is-the-result-of-1-3-0)? – luk2302 Oct 12 '17 at 20:09
  • explain, and give maybe an example – azro Oct 12 '17 at 20:10
  • can you share a sample input and the result you'd like to get for that input? – Mureinik Oct 12 '17 at 20:11
  • What would you expect `div(5, 6, 7, 8)` to return? `sum(5, 6, 7, 8)` is obvious (26). Even `mult(5, 6, 7, 8)` is obvious (1680). But `div(5, 6, 7, 8)`? Is that `5 / 6 / 7 / 8`, i.e. `5 / (6 * 7 * 8) = 5 / 336 = 0.01488`? – Andreas Oct 12 '17 at 20:58

1 Answers1

-1

Well, the difference is that you're gonna have to provide a number to divide as parameter:

public static int div(int div, int ... x)
{
   for(int i : x)
   {
      if(i > 0) div=div/i;
   }
   return div;
 }

Be careful to test if i is greater than 0, otherwise the compiler will throw an error, since you cannot divide by 0.

inafalcao
  • 1,293
  • 1
  • 10
  • 24
  • 1
    Silently ignoring zero divisors is bad. Let it throw division-by-zero exception. Even if you truly want to ignore zeroes, why prevent division by negative numbers? – Andreas Oct 12 '17 at 21:02
  • The op did not specify clearly what he wants, so every assumption is valid. He could want to ignore, or not, we don't know. What I can do is just warn about the division, so he can make something he wants about it. – inafalcao Oct 12 '17 at 21:41