需要帮助了解为什么我通过计算虚数获得非数字输出

时间:2018-06-27 08:41:29

标签: javascript complex-numbers

function ImaginaryNumbers(realNum, imaginary) {
this.realNum = 0;
this.imaginary = 0;
this.realNum = (typeof realNum === 'undefined') ? this.realNum : parseFloat(realNum);
this.imaginary = (typeof imaginary === 'undefined') ? this.imaginary : parseFloat(imaginary);  
}

ImaginaryNumbers.transform = function(num) {
var imaginaryNumbers;
imaginaryNumbers = (num instanceof ImaginaryNumbers) ? num : imaginaryNumbers;
imaginaryNumbers = (typeof num === 'number') ? new ImaginaryNumbers(num, 0) : num;
return imaginaryNumbers;
};

function display_complex(re, im) {
if(im === '0') return '' + re;
if(re === 0) return '' + im + 'i';
if(im < 0) return '' + re + im + 'i';
return '' + re + '+' + im + 'i';
}

function addingComplexNumbers(first, second, third, fourth) {
var num1;
var num2;
num1 = ImaginaryNumbers.transform(document.getElementById("firstComplexNumber").value);
num2 = ImaginaryNumbers.transform(document.getElementById("secondComplexNumber").value);
num3 = ImaginaryNumbers.transform(document.getElementById("thirdComplexNumber").value);
num4 = ImaginaryNumbers.transform(document.getElementById("fourthComplexNumber").value);
var realNum = num1.realNum + num2.realNum + num3.realNum + num4.realNum;
var imaginary = num1.imaginary + num2.imaginary + num3.imaginary + num4.imaginary;
return document.getElementById("result8").innerHTML = display_complex(realNum, imaginary);
}

我尝试获取用户输入,但我不断得到NaN + NaNi,如下所示。我不确定是什么问题。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

您不是从输入中以数字而是字符串形式获取值,因此请使用parseInt来输入整数。

当前为:

num1 = ImaginaryNumbers.transform(document.getElementById("firstComplexNumber").value);
num2 = ImaginaryNumbers.transform(document.getElementById("secondComplexNumber").value);
num3 = ImaginaryNumbers.transform(document.getElementById("thirdComplexNumber").value);
num4 = ImaginaryNumbers.transform(document.getElementById("fourthComplexNumber").value);

更改为:

num1 = ImaginaryNumbers.transform(parseInt(document.getElementById("firstComplexNumber").value));
num2 = ImaginaryNumbers.transform(parseInt(document.getElementById("secondComplexNumber").value));
num3 = ImaginaryNumbers.transform(parseInt(document.getElementById("thirdComplexNumber").value));
num4 = ImaginaryNumbers.transform(parseInt(document.getElementById("fourthComplexNumber").value));