用于具有可变步长的循环 - C ++ [英] For loop with variable step size - C++

查看:155
本文介绍了用于具有可变步长的循环 - C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用一个变量步长的for循环,特别是我希望中的 i 变量代表循环等于:


  1. 所有数字除了可以被 3


    lockquote
    i = 1-2-4-5-7-8-10- ...




    1. 所有数字除外那么可以用 3 2 来区分




    1-5-7-11-13-17 ...


    基本代码:

      #include< iostream> 
    $ b $ int main()
    {
    int N = 100;
    for(int i = 0; i< N; i ++){// <-----
    //指令
    }
    return 0;



    $ b $ p $ 对于循环?

    解决方案

    您可以尝试使用三元运算符。它使得你的代码的可读性更加困难(我认为,但有些人喜欢它),但是你把中的所有内容放在语句中。



    对于可以除以3的数字,例如:

      for(int i = 1 ; i  //指令
    }

    而且,对于可以被3和2分隔的数字,您可以试试这个:
    $ (i = 1;
    i< N;
    i =(i + 1)%3 == 0 ||((i +1)%2)== 0?
    ((i + 2)%3 == 0 || i%2 == 0?
    (i%3 == 0 ||(i + 1)%2 == 0?i + 4:i + 3):i + 2):i + 1){
    //指令
    }

    有关三元运算符的更多信息,请单击这里



    编辑添加@AMA的建议,从评论(比我简单) b
    $ b

      for(int i = 1; 
    i< N;
    i =(i + 1)%2 == 0
    ? (i + 2)%3 == 0
    ? i + 4
    :i + 2
    :(i + 1)%3 == 0
    ? i + 2
    :i + 1){
    //指令
    }


    I want to use a for loop with variable step size, in particular I want that the i variable in for loop is equal to:

    1. All numbers except the ones which can be divided by 3 so:

    i = 1-2-4-5-7-8-10-11-13-14-16-17...

    1. All numbers except the ones which can be divided by 3 and 2 so:

    i = 1-5-7-11-13-17...

    The base code:

    #include <iostream>
    
    int main()
    {
        int N = 100;
        for ( int i=0; i<N; i++) { //<-----
            //instructions
        }
        return 0;
    }
    

    Is it possible with for loop?

    解决方案

    You could try using ternary operators. It makes the readability of your code more difficult (my opinion, but some people like it), but you put everything inside your for statement.

    For the numbers that can be divided by 3, for instance:

    for (int i = 1; i < N; i = (((i+1)%3 == 0) ? i+2 : i+1)) {
        //Instructions
    }
    

    And, for numbers that can be divided by 3 and 2, you could try this:

    for (int i = 1; 
     i < N; 
     i = (i+1)%3 == 0 || ((i+1)%2) == 0 ? 
         ((i+2)%3 == 0 || i%2 == 0 ? 
            (i%3 == 0 || (i+1)%2 == 0 ? i+4 : i+3) : i+2 ) : i+1) {
        //Instructions
    }
    

    For more information about ternary operators, click here

    EDIT Adding @AMA's suggestion, from comments (simpler than mine)

    for (int i = 1; 
         i < N; 
         i = (i+1)%2 == 0 
             ? (i+2)%3 == 0
                 ? i+4
                 : i+2
             : (i+1)%3 == 0 
                 ? i+2
                 : i+1) {
        //Instructions
    }
    

    这篇关于用于具有可变步长的循环 - C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆