【问题标题】:How do you sort numbers in ascending order from a for loop?如何从 for 循环中按升序对数字进行排序?
【发布时间】:2011-11-01 13:03:27
【问题描述】:

我有一个 for 循环,将 3 和 7 乘以 1 到 100 之间的所有数字。它只显示乘法后小于 100 的数字。您将如何对其进行排序以使其按升序排列?

for(int i = 1; i<=100; i++){
int result1 = 3 * i;
int result2 = 7*i;
if (result1 <=100){
System.out.println(+result1);
}
if (result2 <= 100){
System.out.println(+result2);
}
}

会使用另一个 if 语句对其进行排序吗?

【问题讨论】:

    标签: java sorting loops for-loop numbers


    【解决方案1】:

    怎么样:

    for(int i = 1; i<=100; i++){
        if(i % 3 == 0 || i % 7 == 0)
            System.out.println(i);
    }
    

    【讨论】:

    • “%”符号的实际作用是什么?
    • 返回余数 (modulo operation)
    • @ratchetfreak - 例如,这将错过 6 和 9。
    • 所以它基本上只是将数字相除,然后给出小数点是多少?
    • @admjwt 这种方式你必须选择...尝试理解这种方法...不要让事情复杂化...
    【解决方案2】:

    这听起来像它会做你需要的:

    [mike@mike ~]$ cat temp/SO.java 
    package temp;
    
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.List;
    
    public class SO {
        private static final int MAX_VAL = 100;
    
        public static void main(String[] args) {
            List<Integer> results = new ArrayList<Integer>();
    
            for (int i = 1; i <= MAX_VAL; i++) {
                int result1 = 3 * i;
                int result2 = 7 * i;
    
                if (result1 <= MAX_VAL) {
                    results.add(result1);
                }
    
                if (result2 <= MAX_VAL) {
                    results.add(result2);
                }
            }
    
            Collections.sort(results);
    
            System.out.println(results);
        }
    }
    
    [mike@mike ~]$ javac temp/SO.java 
    [mike@mike ~]$ java temp.SO
    [3, 6, 7, 9, 12, 14, 15, 18, 21, 21, 24, 27, 28, 30, 33, 35, 36, 39, 42, 42, 45, 48, 49, 51, 54, 56, 57, 60, 63, 63, 66, 69, 70, 72, 75, 77, 78, 81, 84, 84, 87, 90, 91, 93, 96, 98, 99]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-22
      • 2022-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多