博客
关于我
java的for循环语句,没有实现循环的原因分析
阅读量:502 次
发布时间:2019-03-07

本文共 663 字,大约阅读时间需要 2 分钟。

用for循环实现1-100中偶数的累加

public class ControlWord{   	public static void main(String[] args){   		int s = 0;		for(int i=1; i<101 && i%2==0; i++){   				s += i;		}		System.out.println(s);	}}运行结果输出为0

原因分析:

for循环,只有满足了判断条件才会进入i++循环,一旦不满足就会跳出循环。

这里的判断语句是i<101 && i%2==0,当i=1时条件不满足,跳出循环,输出s=0,无法实现累加

修改代码:

public class ControlWord{   	public static void main(String[] args){   		int s = 0;		for(int i=1; i<101; i++){   			if(i%2==0)				s += i;		}		System.out.println(s);	}}

附:用while实现累加

public class ControlWord{   	public static void main(String[] args){   		int s = 0;		int i = 0;		while(i<=100){   			if(i%2==0){   				s = s + i;			}			i++;		}		System.out.println(s);	}}

转载地址:http://qmbcz.baihongyu.com/

你可能感兴趣的文章
MySQL 证明为什么用limit时,offset很大会影响性能
查看>>
Mysql 语句操作索引SQL语句
查看>>
MySQL 误操作后数据恢复(update,delete忘加where条件)
查看>>
MySQL 调优/优化的 101 个建议!
查看>>
mysql 转义字符用法_MySql 转义字符的使用说明
查看>>
mysql 输入密码秒退
查看>>
mysql 递归查找父节点_MySQL递归查询树状表的子节点、父节点具体实现
查看>>
mysql 通过查看mysql 配置参数、状态来优化你的mysql
查看>>
mysql 里对root及普通用户赋权及更改密码的一些命令
查看>>
Mysql 重置自增列的开始序号
查看>>
mysql 锁机制 mvcc_Mysql性能优化-事务、锁和MVCC
查看>>
MySQL 错误
查看>>
mysql 随机数 rand使用
查看>>
MySQL 面试题汇总
查看>>
MySQL 面试,必须掌握的 8 大核心点
查看>>
MySQL 高可用性之keepalived+mysql双主
查看>>
MySQL 高性能优化规范建议
查看>>
mysql 默认事务隔离级别下锁分析
查看>>
Mysql--逻辑架构
查看>>
MySql-2019-4-21-复习
查看>>