# Thread: what is wrong with this code

1. Member
Join Date
Mar 2008
Posts
31
Rep Power
0

## what is wrong with this code

Hello i have an equality that take the following form:
y = 1-1/2+1/3-......................+1/x
x is avariable entered by the user
I try the following Code but it dosn't Work
Java Code:
```int i,x;
double y=1.0 ;
System.out.print("Please Enter A Number  ");
x = console.nextInt();
for( i = 2;i <= x;i++)
{
if((i % 2) == 0)
y = y + (1 / i);
else
y = y - (1 / i);
i++;
}
System.out.print("The Result OF Y is  "+ y );
}```

2. Please give some more details.

+1 and -1 are fix.

in this case x = 6?

y = 1-1/2+1/3-1/4+1/5-1/6+1

If i am wrong then please correct me.

sanjeev

3. First of all i had to add the code to get the input from the user, not sure if you have this back somewhere in your program, but for me "console" was undefined. Just a few "standard" things, define i in your for loop and dont bother incrementing it in your loop. The for loop does that for you(no pun intended). Also, throw brackets into your if statement. It saves lines leaving them out, but if you ever have to add something in the future you'll forget them and have all kinds of errors, better to just get in the practice of putting them in but that's your preference. The root problem you are having is that your "i" is an integer and is doing integer division. Which 1/x where x>1 is going to end up as a decimal which in integer division will be a zero. We counteract this by thrown a "(double)" in front of it to cast it as a double and force it to do float division. The code below worked for me and should work for you.

Side thought: you mentioned that your equation is y = 1-1/2+1/3-......................+1/x. If that is so then i think your if statement may be backwards. Make it a "!=" to have the even fractions subtracted instead of the odd ones. Right now it is vise verse.
Java Code:
```    int x;
double y = 1.0;
Scanner console = new Scanner(System.in);

System.out.print("Please Enter A Number  ");
x = console.nextInt();
for (int i = 2; i <= x; i++) {
if ((i % 2) == 0) {
y = y + (1 / (double)i);
} else {
y = y - (1 / (double)i);
}
}
System.out.print("The Result Of Y is  " + y);```
Last edited by Chris.Brown.SPE; 04-15-2008 at 05:29 PM.

4. Member
Join Date
Mar 2008
Posts
7
Rep Power
0
public static void main(String[] args) {

double result = 1;
int n = 4;
double m=1;
boolean verno=true;
for(int i=2; i<=n; i++){
if(verno==true){
result = result-m/i;
System.out.println(result+"result0");
verno=false;
}else{result = result+m/i;
System.out.println(result+"result1");
verno=true;
}
}
System.out.println(result);
}

5. Is that supposed to do something different jorjo?

6. Member
Join Date
Mar 2008
Posts
31
Rep Power
0
Thanks to your efforts with me

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•