实验二 流程控制语句
【实验目的】
1.掌握if…else,switch…case分支; 2.掌握for,while,do-while等循环; 3.掌握break,continue跳转语句; 【实验准备】
一、复习配套教材相关章节的内容; 二、预习本次实验; 【实验内容】
1.衡量一个人胖与不胖通用的计算公式是BMI(体重指数)=体重(公斤)除以身高(米)的平方。BMI在18—25属正常范围,大于25为超重,大于30为轻度肥胖,大于35为中度肥胖,大于40为重度肥胖。编写一个程序,实现用户输入体重和身高,显示胖瘦情况。 编写代码: public class Bmi { /**
* @param args the command line arguments */
public static void main(String[] args) { float bmi, weight, height;
Scanner sc = new Scanner(System.in); System.out.println(\请输入体重:\ weight = sc.nextFloat();
System.out.println(\请输入身高:\ height = sc.nextFloat(); bmi = weight / (height * height); if (bmi < 18) {
System.out.println(\偏轻\ } else if (bmi <= 25) {
System.out.println(\正常\ } else if (bmi <= 30) {
System.out.println(\超重\ } else if (bmi <= 35) {
System.out.println(\轻度肥胖\ } else if (bmi <= 40) {
System.out.println(\中度肥胖\ } else {
System.out.println(\重度肥胖\ } } }
输入测试数据和结果: 请输入体重: 62
请输入身高: 1.78 正常
2、使用continue语句实现:将100~300之间的既不能被7整除也不能被11整除的自然数输出。 代码:
public class Continue { /**
* @param args the command line arguments */
public static void main(String[] args) { int i, count = 0;
for (i = 100; i <= 300; i++) { if (i % 3 != 0 && i % 7 != 0) { System.out.print(i + \ count++;
if (count % 10 == 0) { System.out.println(); } } continue;
}// TODO code application logic here } }
运行结果:
100 101 103 104 106 107 109 110 113 115 116 118 121 122 124 125 127 128 130 131 134 136 137 139 142 143 145 146 148 149 151 152 155 157 158 160 163 164 166 167 169 170 172 173 176 178 179 181 184 185 187 188 190 191 193 194 197 199 200 202 205 206 208 209 211 212 214 215 218 220 221 223 226 227 229 230 232 233 235 236 239 241 242 244 247 248 250 251 253 254 256 257 260 262 263 265 268 269 271 272 274 275 277 278 281 283 284 286 289 290 292 293 295 296 298 299
3、输出101-200之间所有素数,并输出共有多少个素数。 素数:除了1和自身没法被别的自然数整除的自然数。 public class Sushu { /**
* @param args the command line arguments */
public static void main(String[] args) { int i, j, count = 0;
for (i = 101; i <= 200; i++) { boolean b = true; for (j = 2; j < i; j++) { if (i % j == 0) { b = false; break; } } if (b) { count++;
System.out.print(i + \ if (count % 10 == 0) { System.out.println(); } } }
System.out.println(\共有\个素数\ } }
运行结果:
101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199
共有21个素数 【总结与体会】
通过本次实验,理解并掌握了流程控制语句,在编写代码的过程中,考虑到显示结果的
相关推荐: