有人可以告诉我程序背后的逻辑吗? [英] Can someone kindly tell me the logic behind the program?
本文介绍了有人可以告诉我程序背后的逻辑吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
// 打印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 numberev
,(ev % 2)
result is0
. On the other hand, for every odd numberod
,(od % 2)
result is1
.
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屋!
查看全文