James Kyle
James Kyle

Reputation: 4178

Javascript while loop calculation

I wouldn't run this if I were you:

Javascript:

(function() {
    var a = 1, 
        b = a, 
        c = b,
        d = 1,
        e = 1;

    while ( d != 0 && e != 0) {
        b = Math.sqrt(a*a+a*a);
        c = 2*a-b;

        e = b%1;
        f = c%1;

        document.write(a);

        a++;
    } 

    document.write('a = ' + a);
    document.write('b = ' + b);
    document.write('c = ' + c); 

})();​

Yeah basically I want to calculate the same equation over and over again until all three are integers with Javascript and then print them out. Please know that up until recently I only used jQuery.

This seems to just repeat infinitely though I find it weird that it does not print a while calculating, not sure if thats how the javascript while loop works.

Also, why can't i use Math.sqrt(2a^2) to calculate B?

Upvotes: 0

Views: 2001

Answers (2)

Paul
Paul

Reputation: 141877

Math.sqrt(2a^2) doesn't work because:

1) You must be explicit in Javascript when you want multiplication by using *. 2a doesn't mean 2*a.
2) ^ has a different meaning in Javascript than exponentiation. It means Bitwise XOR

Both those are true in many other programming languages as well. Math.sqrt(2*a*a) would work for you.

Your loop doesn't exit because d != 0 is always going to be true since you never modify d from it's original value of 1.

I'm not sure what you are trying to do with b%1 and c%, but any integer mod 1 will give you 0.

Nothing is written to the screen because your loop doesn't ever stop executing and therefore doesn't give a web browser a chance to render anything.

Upvotes: 3

Brandan
Brandan

Reputation: 14983

It never ends because d will never equal 0. You initialize it to 1 and never reassign it. You're also using an undeclared variable f. Is that supposed to be d?

I'd also suggest using console.log instead of document.write. It's flushed more frequently than the DOM and typically has much better logging capabilities. Check out the WebKit Inspector (Safari and Chrome), Firebug (Firefox), or the F12 Developer Tools (IE).

As PaulP.R.O. pointed out, your desired syntax for exponentiation is invalid JavaScript syntax. You could write it like this if you wanted to:

b = Math.sqrt(2 * Math.pow(a, 2));

Upvotes: 3

Related Questions