简体   繁体   中英

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 "

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. 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.

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. 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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM