2011-10-24 28 views
1
// Write a program to sum all the odd elements of an array 

    a = Number(prompt("a:")); 
    b = Number(prompt("b:")); 
    c = Number(prompt("c:")); 

    sum=Number(0); 

    var test = [a,b,c]; 

    for (i=0; i<test.length;i++) { 
     // All even numbers can be divided by 2 
     if ((test[i]%2)>0) { 
      alert(test[i] + ":odd"); 
     } else { 
      alert(test[i] + ":even"); 
     } 
     test[i]=0; 
    } 

    sum=0+test[i]; 
    alert(sum); 

我的程序很精彩,直到它的意思是把所有的數字加起來,它返回一個NaN消息!關於如何解決這個問題的任何想法?編寫一個程序,將一個數組中的所有奇數加起來

+2

值輸入的字符串,而不是數字,這應該是足夠的提示。 –

+1

我看到第二個問題,因爲你的總和總是等於最後添加的數字,它不是總結,而是設置。 –

+3

@Dave:除了Number('11')+ Number('23')'是34. –

回答

6

我看到你的代碼有三個問題。 (不算大括號的怪異格式。)

  1. 編輯:看起來像這個問題已經更新了好幾次,因爲我開始我的答案。在「如果奇數」測試中,您將數字設置爲零與也許您的意思是將偶數整理爲零,以便稍後可以累加所有數字並獲得奇數,但test[i]=0不是if/else結構。它看起來像應該是因爲縮進,但JavaScript忽略額外的空白。

  2. 您不會在循環中將數字添加到sum

  3. 你得到,因爲這條線的楠:

    sum=0+test[i]; 
    

這項聲明是循環的結尾之外,所以在這一點上i等於陣列和test[i]是長度undefined

試試下面的僞代碼:

sum = 0 
for (loop through the array) { 
    if current number is odd 
     sum = sum + current number 
} 
+1

'sum + =當前數字'甚至 – btleffler

+1

@btleffler - 是的,我肯定會這樣編碼,但我故意沒有說出來,因爲它看起來像jeansymolanza已經足夠困惑,沒有引入更多的操作員...... – nnnnnn

4

您的總和(sum = 0 + test [i];)在for循環之外。你應該在for循環中移動它以獲得你的「sum」變量的總和。

4
var A= [17, 6, 19, 27, 56, 73, 43, 70, 41, 48, 
10, 69, 22, 71, 53, 11, 40, 72, 32, 25, 14, 54, 
13, 38, 62, 66, 2, 37, 60, 75, 52, 33, 58, 30, 
61, 5, 57, 49, 21, 34, 67, 51, 16, 45, 64, 24, 
23, 20, 47, 65, 46, 18, 1, 44, 15, 42, 68, 26, 
74, 7, 55, 36, 8, 50, 9, 59, 31, 3, 4, 29, 
35, 39, 63, 12, 28]; 

A.filter(function(i){return i%2}).reduce(function(a, b){return a+b}); 

返回值:(數字)從提示1444

//equalizer for old browsers 
if(![].filter){ 
    Array.prototype.filter= function(fun, scope){ 
     var T= this, A= [], i= 0, itm, L= T.length; 
     if(typeof fun== 'function'){ 
      while(i< L){ 
       if(i in T){ 
        itm= T[i]; 
        if(fun.call(scope, itm, i, T)) A[A.length]= itm; 
       } 
       ++i; 
      } 
     } 
     return A; 
    } 
} 
if(![].reduce){ 
    Array.prototype.reduce= function(fun, temp, scope){ 
     var T= this, i= 0, len= T.length, temp; 
     if(typeof fun=== 'function'){ 
      if(temp== undefined) temp= T[i++]; 
      while(i < len){ 
       if(i in T) temp= fun.call(scope, temp, T[i], i, T); 
       i++; 
      } 
     } 
     return temp; 
    } 
} 
相關問題