javascript 判断一个数是否能被 3 或 5 整除 (FizzBuzz)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31106668/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Find if a number is divisible by 3 or 5 (FizzBuzz)
提问by Corey Blinks
How do I change the output depending on whether or not it is divisible by 3 or 5? If it is divisible by 3, I want to show "rock" and if it's divisible by 5 I want to show "star" (similar to in FizzBuzz). If both, they'll see both.
如何根据输出是否可被 3 或 5 整除来更改输出?如果它可以被 3 整除,我想显示“rock”,如果它可以被 5 整除,我想显示“star”(类似于在 FizzBuzz 中)。如果两者都有,他们就会看到。
Here's my code:
这是我的代码:
if (var n = Math.floor((Math.random() * 1000) + 1); {
var output = "";
if (n % 3 == 0)
output += "Rock";
if (n % 5 == 0)
output += "star";
prompt(output || n);
}
Why isn't my code working properly?
为什么我的代码不能正常工作?
回答by Burning Crystals
var n = Math.floor((Math.random() * 1000) + 1);
if (n) {
var output = "";
if (n % 3 == 0)
output += "Rock";
if (n % 5 == 0)
output += "star";
prompt(output || n);
}
The var
inside the if
statement is a syntax error. My browser shows this error:
在var
里面if
的语句是一个语法错误。我的浏览器显示此错误:
SyntaxError: expected expression, got keyword 'var'
So I think you should declare variable n
before telling the if
statement that var n
is your comparison expression.
所以我认为你应该n
在告诉你的比较表达式的if
语句之前声明变量var n
。