了解C#中的嘶嘶声 [英] understanding the fizz buzz in C#
问题描述
在使用"while"循环解决C#中的"fizz-buzz"问题时,我发现首先应该找到3和5的倍数(15的倍数),然后再像3和5的倍数一样以下.
When solving "fizz-buzz" in C# using a "while" loop, I found out that first I should find the multiples of both 3 and 5 (multiples of 15) and then go to the multiples of 3 and 5 like below.
int myval = 0;
while (myval < 100)
{
myval = myval + 1;
if (myval % 15 == 0)
{
listBox1.Items.Add("fizzbuzz");
}
else if (myval % 3 == 0)
{
listBox1.Items.Add("fizz");
}
else if (myval % 5 == 0)
{
listBox1.Items.Add("buzz");
}
else
{
listBox1.Items.Add(myval);
}
}
但是,如果我编写代码先过滤3和5的倍数,然后转到3和5的倍数(15的倍数),如下所示,最终结果只会显示嘶嘶声(3的倍数)和嗡嗡声( 5的倍数)而没有嘶嘶声(3和5的倍数).有谁知道这个IDE的原因是什么?
But if I write the code to filter multiples of 3 and 5 first and then go to the multiples of both 3 and 5 (multiples of 15) like below the end result only shows the fizz (multiples of 3) and buzz (multiples of 5) without fizz-buzz (multiples of both 3 and 5). Does anyone know what's the reason for this even IDE doesn't show me any errors.
myval = 0;
while (myval < 100)
{
myval = myval + 1;
if (myval % 3 == 0)
{
listBox1.Items.Add("fizz");
}
else if (myval % 5 == 0)
{
listBox1.Items.Add("buzz");
}
else if (myval % 15 == 0)
{
listBox1.Items.Add("fizzbuzz"); // for multiples of both 3 and 5
}
else
{
listBox1.Items.Add(myval);
}
}
推荐答案
这归结为if-else
语句是按顺序处理的事实.一旦遇到求值为true
的条件,就会跳过其他else if
子句.
This boils down to the fact that if-else
statements are processed sequentially. As soon as a condition that evaluates to true
is encountered, the other else if
clauses are skipped.
假设a
和b
均为true
.当您写
if (a) {
Foo1();
}
else if (b) {
Foo2();
}
您不会同时执行Foo1
和Foo2
.因为a
是true
,所以执行Foo1
甚至不评估b
.
you do not execute both Foo1
and Foo2
. Since a
is true
, Foo1
executes and b
is not even evaluated.
现在考虑您的问题.考虑数字15.所有三个候选除数3、5和15均除以该数字.
Now consider your problem. Consider the number 15. All three candidate divisors, 3, 5 and 15, divide into that number.
if (myval % 3 == 0)
{
listBox1.Items.Add("fizz");
}
else if (myval % 5 == 0)
{
listBox1.Items.Add("buzz");
}
else if (myval % 15 == 0)
{
listBox1.Items.Add("fizzbuzz"); // for multiples of both 3 and 5
}
else
{
listBox1.Items.Add(myval);
}
由于15
的倍数也是3
(和5
)的倍数,因此您甚至都不会达到myval % 15 == 0
的15
倍数测试.
Since the multiples of 15
are also multiples of 3
(and 5
), you will never even reach the myval % 15 == 0
test for multiples of 15
.
这篇关于了解C#中的嘶嘶声的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!