This is a read-only archive of the old Scratch 1.x Forums.
Try searching the current Scratch discussion forums.

#1 2011-06-24 07:07:31

matthew8092001
Scratcher
Registered: 2010-09-12
Posts: 100+

Java help #2

Lol I shouldn't be posting this here...but anyway, I'm trying to find a summation 1/(a+b)
where it repeats 100 times and a and b both increase by 1 every time. This is what I have so far, and it looks right, but I keep on getting 0 D:

Code:

public class Summation {

    public static void main(String[] args) {
        int a = 1;
        int b = 2;
        double result = 1/(a+b);
        int beginloop;
        int endloop=100;
        for (beginloop = 1;beginloop<endloop;beginloop++){
            a = a+1;
            b = b+1;
            result = result + 1/(a+b);
        }
        System.out.println(result);
    }
}

Last edited by matthew8092001 (2011-06-24 07:12:23)


http://1.bp.blogspot.com/_GVA115I1I8Y/TMGwbJ056kI/AAAAAAAABHs/kpvg0oCKV2g/s1600/happy.gif
lol

Offline

 

#2 2011-06-24 08:54:30

archmage
Scratcher
Registered: 2007-05-18
Posts: 1000+

Re: Java help #2

Ok, there is a few things I think that would make your code better.

1. The variables in your for loop should all be local to that loop

example pulled from google:

class ForDemo {
     public static void main(String[] args){
          //loop 10 times
          for(int i=1; i<11; i++){
               System.out.println("Count is: " + i);
          }
     }

2. Use proper addition operators

don't use result= result + 1
Use instead result+=1
}

If you want to add 1 to a number just use ++
ex:
a++;
is the same as a=a+1;

3. This  result = result + 1/(a+b);
is incorrect

It should be  result = (result + 1)/(a+b);
or simply  result += 1/(a+b);

If that still doesn't work change all your number variables to doubles.


Hi, I am Archmage coder extraordinaire. I do Scratch,pascal,java,php,html, AS2 and AS3. Leave me a message if you want coding advice. Also check out my personal website, lots of good stuff about web development, Flash, and Scratch (v1 and v2) !

Offline

 

Board footer