[英]IS there any way i can make this shorter
I am learning how to use untiy in my spare time by reading a beginners book and looking up stuff online in the book there is a exercise that asks me 通过阅读初学者的书并在线查找书中的内容,我正在学习如何在业余时间使用不整洁,有一个练习要求我
to create a script that outputs the numbers from 1 to 10 in to the console but dose not output any multiple of 3 and 5 instead outputting the phrase "programming is awesome "
创建一个脚本,将数字从1到10输出到控制台,但不输出3和5的倍数,而是输出短语“ programming is awesome”
while i have achieved this task by using this code 虽然我通过使用此代码实现了此任务
using UnityEngine;
using System.Collections;
public class Loops : MonoBehaviour {
// Use this for initialization
void Start () {
for(int i = 1; i <= 10; i++)
{
if(i == 3 )
print ("Programming is Awesome!");
else if (i == 5)
print ("Programming is Awesome!");
else if (i == 6)
print ("Programming is Awesome!");
else if (i == 9)
print ("Programming is Awesome!");
else if (i == 10)
print ("Programming is Awesome!");
else
print (i);
}
}
}
i was wondering if there was any way to achieve the same result only by using less lines of code 我想知道是否只有通过使用较少的代码行就能达到相同的结果
You want to use the modulus (aka modulo) operator (%) for this task. 您要使用模数(aka模)运算符(%)来完成此任务。 It returns the remainder of a division, so when the result of a modulus operation is 0 you know you have a multiple of the divisor.
它返回除法的余数,因此,当模运算的结果为0时,您就知道除数是倍数。
for (int i = 1; i <= 10; i++)
{
if(i % 3 == 0 || i % 5 == 0)
print("programming is awesome");
else
print(i);
}
The point of this exercise is that you should calculate the multiples, not just make one condition for every value that you know is a multiple. 本练习的重点是您应该计算倍数,而不仅仅是为您知道是倍数的每个值都设定一个条件。
Use the modulo operator to check it a number is an even multiple of another. 使用模运算符检查它是否为另一个的偶数倍。 This shows what the modulo operator returns for some values:
这显示了模运算符对于某些值返回的内容:
i i % 3
------------
1 1
2 2
3 0
4 1
5 2
6 0
7 1
As you see, i % 3
evaluates to 0
when i
is a multiple of three. 如您所见,当
i
为3的倍数时, i % 3
值为0
。 You can use that to check if the number is a multiple of three: 您可以使用它来检查数字是否为三的倍数:
if (i % 3 == 0) {
print ("Programming is Awesome!");
}
Now you should be able to do the same for five also, and incorporate it in your code. 现在,您应该也可以对五个执行相同的操作,并将其合并到您的代码中。
for (int i = 1; i <= 10; i++)
{
print((i % 3 == 0 || i % 5 == 0)? "programming is awesome" : i));
}
check out also using ternary operator. 也可以使用三元运算符进行检出。
Ways of doing this 这样做的方式
if(i == 3 || i == 5 || i == 6 || i == 9 || i == 10){
print ("Programming is Awesome!");
}
else {
print (i);
}
Better way By Using the modulo operator 使用取模运算符的更好方法
if( i % 3 == 0 || i % 5 == 0){
print ("Programming is Awesome!");
}
else {
print (i);
}
Use can also try 使用也可以尝试
print((i % 3 == 0 || i % 5 == 0)? "Programming is Awesome!" : i));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.