【问题标题】:Javascript. Wrong comparison outputJavascript。错误的比较输出
【发布时间】:2018-07-03 22:22:11
【问题描述】:
fs.readFile('./input.txt', (error, data) => {
if(error)
    console.log(error);
const input = data.toString();
const dataArray = input.split(/[\n\r ]+/);
const lastItem = dataArray.length;
let accumulator = 0;
let counter = 0;
for(let i=0; i<lastItem-1; i++) {
    let tempArray = dataArray[i];
    let splitArray = tempArray.split('x');
    let a = splitArray[0];//length
    let b = splitArray[1];//width
    let c = splitArray[2];//height
    let d = a<b? (b<c?c:b) : (a<c?c:a);
    let output = 0;
    if(d === a)
        output = (2*b + 2*c + a*b*c);
    else if(d === b)
        output = (2*a + 2*c + a*b*c);
    else
        output = (2*b + 2*a + a*b*c);   
    accumulator += output;
}})

输入: 3x11x24 13x5x19 1x9x27

这是我的代码和输入。而且我想知道为什么我得到错误的比较来得到'd'数字。我希望 'd' 是输入中每 3 个数字中最大的一个。 对我来说真正奇怪的是,当我想 console.log(a

【问题讨论】:

    标签: javascript syntax-error comparison


    【解决方案1】:

    在您的代码中,a、b、c 是字符串。你正在分割一个字符串,结果你得到一个字符串。您需要转换为一个数字。

    let a = +splitArray[0];//length
    let b = +splitArray[1];//width
    let c = +splitArray[2];
    

    将字符串转换为数字,您的比较将起作用

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-30
      • 1970-01-01
      • 1970-01-01
      • 2017-06-28
      • 2019-01-03
      • 2014-09-07
      相关资源
      最近更新 更多