使用规则打印1至20之间的数字 [英] print numbers between 1- 20 using rules
问题描述
由于我是新手,所以我正在阅读codeacademys的JavaScript教程.本教程要求以下内容:
I am going through codeacademys JavaScript tutorials as i am new to it. The tutorial asks for the following:
打印1到20之间的数字.
规则:
-对于要被3整除的数字,请打印"Fizz".
-对于可被5整除的数字,请打印出嗡嗡声".
-对于可被3和5整除的数字,请在控制台中打印出"FizzBuzz".
-否则,只需打印出数字即可.
Print out the numbers from 1 - 20.
The rules:
- For numbers divisible by 3, print out "Fizz".
- For numbers divisible by 5, print out "Buzz".
- For numbers divisible by both 3 and 5, print out "FizzBuzz" in the console.
- Otherwise, just print out the number.
这是我的代码:
for (i=1; i<=20; i++) {
if(i%3==0) {
console.log("Fizz");
}
if(i%5==0){
console.log("Buzz");
}else if (i%5==0 && i%3==0) {
console.log("fizzBuzz");
} else {
console.log(i);
}
}
我收到一条错误消息,说我打印出错误数量的项目,有人知道为什么吗?
i am getting an error saying that i am printing out the wrong number of items, anyone know why that is?
推荐答案
当值被3而不是5整除时,将在第一个If语句上打印"Fizz".
When the value is divisible by 3 and not by 5, on the first If statement "Fizz" is printed.
然后在第二个if语句上,命中最后一个else,因此也会打印该数字.您将需要将if(i%5 == 0)更改为else if.
Then on the second if statement, the last else is hit so the number will also be printed. You will need to change the if(i%5==0) to else if.
但是,当(i%5 == 0&& i%3 == 0)时,将出现问题,否则将永远无法实现.您可以通过将其作为第一个比较并将输出更改为FizzBuzz来解决此问题.
However there will be a problem now when (i%5==0 && i%3==0) as the else if for that will never be hit. You can fix this by putting this as the first comparison and changing the output to FizzBuzz.
赞:
for ( i = 1; i <= 20; i++) {
if (i % 5 === 0 && i % 3 === 0) {
console.log("FizzBuzz");
} else if (i % 3 === 0) {
console.log("Fizz");
} else if (i % 5 === 0) {
console.log("Buzz");
} else {
console.log(i);
}
};
在继续操作之前,请确保您理解为什么这可以解决您的问题,因为您很可能会再次犯同样的错误.
Make sure you understand why this fixes your issue before you move on as you will most likely make the same mistake again.
如果您想让我更清晰地说明您是否正在努力找出错误原因,请添加评论.
Add a comment if you would like me to explain clearer if you are struggling to work out why you have gone wrong.
这篇关于使用规则打印1至20之间的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!