星期一, 4月 14, 2008

Partial Answer to Quiz 2

Partial solutions: The following solutions are not complete Java programs. They are kept brief to illustrate the main ideas of the complete programs.

Problem 1:

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

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;
}
}


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

int evenSum=oddSum=0;

for(i=1; i<=50; i++)
{
if(i%2==0)
evenSum=evenSum+i;
else
oddSum+=i;

}

沒有留言: