繁体   English   中英

HackerRank 问题 PlusMinus 使用 for-loop

[英]HackerRank problem PlusMinus using for-loop

对于这个特定的 HackerRank 问题,我需要非常具体的答案: https://www.hackerrank.com/challenges/plus-minus/problem

为什么这段代码通过了所有的测试用例?

function plusMinus(arr) {
let positives = 0
    let negatives = 0
    let zeros = 0
    const length=arr.length

    for (var i = 0; i < arr.length;i++){
        if (arr[i] > 0) {
            positives++
        } else if (arr[i] < 0) {
            negatives++
        } else {
            zeros ++
        }
    }

    const positiveRatio = Number(positives / length).toFixed(6)
    const negativeRatio = Number(negatives / length).toFixed(6)
    const zeroRatio = Number(zeros / length).toFixed(6)

    console.log(positiveRatio)
    console.log(negativeRatio)
    console.log(zeroRatio)
}

为什么这段代码没有通过任何测试用例? (我已经编辑了我的代码:抱歉之前的错误代码)此代码也不起作用。

function plusMinus(arr) {
var l = arr.length;
var positiveCounter = 0;
var negativeCounter = 0; 
var zeroCounter = 0;

for(var i=0; i<=l; i++) {
    if (arr[i]>0) { 
        positiveCounter+=1;
    } else if (arr[i]<0) { 
        negativeCounter+=1; 
    } else { 
        zeroCounter+=1; 
    }
}

console.log (
(positiveCounter/l).toFixed(6)+ '\n' +(negativeCounter/l).toFixed(6)+ '\n' +(zeroCounter/l).toFixed(6) );
 }

我不想要其他方法来解决这个问题。 我只想知道为什么第一个代码有效而第二个代码无效???

这两个代码不同,您将数字除以长度两次

  • 首先在分配给一个变量( var p=...
  • 第二次做 console.log ( (p/l).toFixed(6) )

此外,就像@DhananjaiPai 提到的那样,它们有多个console.log ,而您只有一个带有中断字符,操作系统可能会以不同方式解释( \r\n\n

您的循环中也有问题,我会让您找到那个,但请记住数组从索引 0 开始,如果数组有 3 个元素,则为[0, 1, 2]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM