Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
299 views
in Technique[技术] by (71.8m points)

javascript - Why is my FizzBuzz code not outputting correctly?

function counter(numOne, numTwo) {
  for (let i = 0; i <= 100; i++) {

    if (i % numOne === 0) {
      console.log("Fizz");
    }
    if (i % numTwo === 0) {
      console.log("Buzz");
    }
    if (i % numOne === 0 && i % numTwo === 0) {
      console.log("FizzBuzz");
    }
    else if (i <= 100 && i !== i % numOne === 0 || i !== i % numTwo === 0) {
      console.log(i);
    }
  }
}

counter(3, 5);

For the else if loop, it should console.log all numbers that are <=100, but are not i % numOne === 0 and i % numTwo === 0. So why are only Fizz, Buzz, and FizzBuzz showing up in the output?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Ok, I didn't want to write an answer but since you're new here, I'll put this in a more meaningful way:

function counter(numOne, numTwo) {
  for (let i = 0; i <= 100; i++) {
    const isFizz = i % numOne === 0
    const isBuzz = i % numTwo === 0

    if (isFizz && isBuzz) {
      console.log("FizzBuzz");
    }
    else if (isFizz) {
      console.log("Fizz");
    }
    else if (isBuzz) {
      console.log("isBuzz")
    }
    else {
      console.log(i);
    }
  }
}

counter(3, 5);

In your example, you had:

i !== i % numOne === 0

as stated above, there are two issues here:

  1. i !== i can never be true, it's the same value, it's always i === i or in your case false
  2. Since the above is false, you'll have a math equation of: false % numOne this will result in a NaN and NaN does not equal 0

Hope this and the comments above helps understand your issue


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...