Sun JunXu wrote:

> > hi, all:
> > got a question:
> > following is an exam.
> >
> > class Prob2 {
> >       public static void main (String [] args) {
> >               int arr[]=new int[args.length];
> >               float var1=0;
> >
> >               for (int i=0;i<args.length;i++)
> >                       arr[i]=(new Integer(args[i])).intValue();
> >               for (int i=0;i<arr.length;i++)
> >                       var1=(i%2==0)?0:arr[i];
> >               System.out.println(var1/args.length);
> >       }
> > }
> >
> >
> > what is result when you run:
> > java Prob2 20 45 60 85 100 205 300 405
> >
> > I don't understand what it is meaning that "var1=(i%2==0)?0:arr[i];"
> > who can explain it to me?
> >

%  is the modulo operator. Modulo is the 'left-over' in a integer division.
So,  15 / 4 = 3, and 15 % 4 = 3, because;  3*4=12, 12+3=15.
So, i%2 is giving you a series of 0,1,0,1,0,1,0, when i is incremented.

Secondly, the tertiary (operator with three operands) ?: is a classic C
favourite.
booleanexpr ? trueexpr : falseexpr
meaning, if the boolean expression to  the left of the question mark is true,
the trueexpression is calculated and returned, otherwise the false expression.

Your code above is equivalent to

if( i % 2 == 0 )
   var1 = 0;
else
    var1 = arr[i];

So the answer is (if the code is copied properly);
50
var1 is finally assign to the last input value, and that is integer divided by
8 (number of arguments on the commandline.

Niclas



------------------------------------------------------------
To subscribe:    [EMAIL PROTECTED]
To unsubscribe:  [EMAIL PROTECTED]
Problems?:       [EMAIL PROTECTED]

Reply via email to