2016-06-06 3 views
0

Hier ist mein Code, der t work. It seems to me that it has to but when I use console (in inspect section in the browser) nothing happens, it doesn t keinen Fehler findet.Ist es möglich, die Zeile von 2 in der Potenz von 1,2 ... 10 (die größte) mit While-Schleife mit Math.pow?

I `d sehr dankbar, wenn Sie mir erklären, wo ist der Fehler (-s)

var counter = 0; 
var result = Math.pow (2, counter); 
    while (result < Math.pow (2, 10)) { 
    console.log(result); 
    counter = counter + 1; 
    } 
+2

Sie wechseln Zähler in Ihrem während aber nie Ergebnis ändern – juvian

Antwort

0

Wie juvian in der angegebenen Kommentare, Sie aktualisieren die Variable "Counter" in Ihrer While-Schleife, aber Sie müssen auch "Ergebnis" in jeder Schleife aktualisieren. Hier ist eine überarbeitete Version Ihres Codes mit einer Erläuterung.

// Counter starts at zero 
var counter = 0; 

/* 
    Result needs to be initialized to check the 
    initial condition. 

    Alternatively, we could have changed the 
    condition of the while loop to something like: 
    while (counter <= 10) { ... } 

    (this would be technically faster because 
    you're not re-computing Math.pow(2,10)) 
*/ 
var result = 0; 

// We perform the code in here until the condition is false 
while (result < Math.pow (2, 10)) { 
    // First, we raise 2 to the power of counter (0 the first time) 
    var result = Math.pow (2, counter); 
    // Print the result 
    console.log(result); 
    // Now increment the counter 
    // (this will change what the first line of the loop does) 
    counter = counter + 1; 
} 
+0

, wie die Schleife beginnt, wenn es doesn 't wissen, was das Ergebnis ist (und daher, ob es' s größer oder kleiner als Math.pow (2, 10))? –

+0

Oh, Sie heben einen guten Punkt. Sie könnten das Ergebnis auf Null initialisieren, um dies zu korrigieren. Ich werde meinen Code entsprechend bearbeiten. –

0

Eine alternative Möglichkeit, dies zu schreiben wäre:

var result = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(function (num) { 
    return Math.pow(2, num) 
}) 
0

Der inkrementierte Zähler wird nie in der Ergebnisberechnung verwendet. Versuche dies.

var counter = 0; 
while (Math.pow (2, counter) < Math.pow (2, 10)) { 
    console.log(Math.pow (2, counter)); 
    counter = counter + 1; 
} 
Verwandte Themen