星期五, 10月 31, 2008

Answer to Quiz

1. Write a Java program to calculate the trianular function as follows:
Cos(x)=1 - 2!/x 2 + 4!/x 4- 6!/x 6...

double power=1, fact=1, sum=0;
int k=-1;

for(int i=1; i<10; i++)
{
power=power*x;
fact=fact*i;
if(i%2==1)
{ k=k*(-1);
sum+=k*power/fact;
}
}


6. Write a complete Java program that uses a for loop to compute the sum of odd numbers between 1 and 25.

int evenSum=oddSum=0;

for(i=1; i<=25; i++)
{
if(i%2!=0)

oddSum+=i;

}

沒有留言: