在每三次迭代中,C# [英] On every third iteration C#
问题描述
我有这个循环,每当我的变量是3的倍数时,它就会为我执行一个简单的任务,目前我必须创建一个大循环,其中包含3的每一个倍数,并具有逻辑或(3、6、9, ...).我想知道是否有更有效的方法来做到这一点.
I have this loop which is performing a simple task for me every time my variable is a multiple of 3, currently I have to create a big loop which contains every multiple of 3 with a logical OR (3, 6, 9, ...). I am wondering if there is a more efficient way of doing this.
这是我的代码段:
if (waveCounter == 3 || waveCounter == 6 || waveCounter == 9 || waveCounter == 12)
{
amount = 0.03f;
dayNight.lightAmout = amount;
dayNight.light.intensity = Mathf.Lerp(dayNight.light.intensity, dayNight.lightAmout, fadeTime * Time.deltaTime);
}
else
{
amount = 1f;
dayNight.lightAmout = amount;
dayNight.light.intensity = Mathf.Lerp(dayNight.light.intensity, dayNight.lightAmout, fadeTime * Time.deltaTime);
}
我的目标是摆脱在if语句中写入3的那些倍数,并且每次我的waveCounter变量是3的下一个倍数时仍然达到相同的目标.
My objective here is to get rid of writing those multiples of 3 in the if statement and still achieving the same goal every time my waveCounter variable is the next multiple of 3.
推荐答案
if((waveCounter % 3) == 0)
模运算:将数字除以3,然后检查余数.可除以3的数字没有余数(因此是==0
)
Modulo arithmetic: it divides a number by 3 and checks for the remainder. A number that is divisable by 3 has no remainder (and thus ==0
)
这篇关于在每三次迭代中,C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!