有人可以告诉我程序背后的逻辑吗? [英] Can someone kindly tell me the logic behind the program?

查看:75
本文介绍了有人可以告诉我程序背后的逻辑吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  //  打印0到100之间的偶数 

class ContDemo {
public static void main( String args []){
int i;

for (i = 0 ; i< = 100; i ++){

if ((i%2)!= 0 继续; // iterate

System.out.println(i);
}
}
}

解决方案

它只是跳过奇数。

由于运算符提供了整数除法的提示,因此对于每个偶数数字 ev (ev%2)结果是 0 。另一方面,对于每奇数数字 od (od%2)结果是 1



你知道,一个更高效的算法将是

< pre lang =java> public static void main( String args [])
{
int i;

for (i = 0 ; i< = 100; i + = 2 )
{
System.out.println(i);
}
}


// prints even numbers between 0 and 100

    class ContDemo {
    public static void main(String args[]) {
    int i;
    
    for(i = 0; i<=100; i++) {

    if((i%2) != 0) continue; // iterate

    System.out.println(i);
    }
   }
 }

解决方案

It simply skips odd numbers.
Since the % operator gives the reminder of the integer division, for every even number ev, (ev % 2) result is 0. On the other hand, for every odd number od, (od % 2) result is 1.

You know, a more efficient algoritm would be

public static void main(String args[]) 
{
  int i;

  for(i = 0; i<=100; i+=2) 
  {
    System.out.println(i);
  }
}


这篇关于有人可以告诉我程序背后的逻辑吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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