# what is wrong with this code

• 04-15-2008, 03:14 PM
masaka
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
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 );        }```
• 04-15-2008, 03:54 PM
sanjeevtarar

+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
• 04-15-2008, 06:25 PM
Chris.Brown.SPE
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.
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);```
• 04-15-2008, 09:17 PM
saint_jorjo
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);
}
• 04-15-2008, 09:59 PM
Chris.Brown.SPE
Is that supposed to do something different jorjo?
• 04-16-2008, 09:27 AM
masaka
Thanks to your efforts with me