迭代结果的总和?

时间:2016-03-10 18:48:59

标签: javascript html

我编写了一个程序,用于将基数2转换为基数为10的数字。这是我的代码片段:



function translateToBaseTen()
	{
     
      var inputNumber = document.getElementById('BaseTwoNumberButton').value;
		
      
      var i = 0;
      var text = "";
      var text2 = "";
      var lengthOne = inputNumber.length;
      var j = (lengthOne-1);
      
   
     

     while (i < 12 && lengthOne < 12 )
				{
    
     var resolved = (inputNumber[i] * Math.pow(2,j));
	text += "<br>Number " + (i+1) + " = " + inputNumber[i];
                  
    text2 += "<br>Number " + (i+1) + " ,Value on base ten =  " + resolved + " /// Description :==> " + " ( " + inputNumber[i] + " * (2^" + j + ") )";
     
                  i++;
                  j--;
               
                  
      if (inputNumber[i] === undefined) {
        break;
      
      } 
      
          
}
     document.getElementById('demo').innerHTML = text;
     document.getElementById('demo2').innerHTML= text2;
        }
&#13;
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Base Arithmetic 1.0</title>
  </head>
<body>
  <p id="demo">a</p><br>
  <p id="demo2">b</p><br>
  <input type="number" value="0" id="BaseTwoNumberButton" maxlength="2"><br><br>
  <input type ="button" value="Resolve" onClick="translateToBaseTen()"><br>
 
</body>
</html>
&#13;
&#13;
&#13;

当我输入&#34; 0101&#34; ,结果通常是:

Number 1 ,Value on base ten = 0 /// Description :==> ( 0 * (2^3) )
Number 2 ,Value on base ten = 4 /// Description :==> ( 1 * (2^2) )
Number 3 ,Value on base ten = 0 /// Description :==> ( 0 * (2^1) )
Number 4 ,Value on base ten = 1 /// Description :==> ( 1 * (2^0) )

问题是,我需要得到(0,4,0,1)的和才能获得真正的转换结果。有可能这样做吗?

3 个答案:

答案 0 :(得分:3)

创建一个变量sum并在循环中添加sum + = resolved。

答案 1 :(得分:0)

您可以在while循环之前将整体值存储为变量,每次循环时添加基数10值,并在其他所有内容后打印输出。请查看下面的 var output

function translateToBaseTen()
{
  var inputNumber = document.getElementById('BaseTwoNumberButton').value;

  var i = 0;
  var text = "";
  var text2 = "";
  var lengthOne = inputNumber.length;
  var j = (lengthOne-1);

  var output = 0;

  while (i < 12 && lengthOne < 12 ) {

  var resolved = (inputNumber[i] * Math.pow(2,j));
  text += "<br>Number " + (i+1) + " = " + inputNumber[i];

  text2 += "<br>Number " + (i+1) + " ,Value on base ten =  " + resolved + " /// Description :==> " + " ( " + inputNumber[i] + " * (2^" + j + ") )";

  //Add value on base ten to output
  output += resolved;

      i++;
      j--;

  if (inputNumber[i] === undefined) {
    break;
    }          
  }

  //Print output here:
  text2 + = "<br>Output: " + output;
}

答案 2 :(得分:0)

你可以这样做

var total = 0;
total += resolved;

在这里工作JSFiddle https://jsfiddle.net/xLwr21Lj/1/