day05作业题干
代码题
题目8
求1-100之间的和。
package com.itheima.demo;
public class Test01 {
public static void main(String[] args) {
int sum=0;
for (int i = 1; i <= 100; i++) {
sum+=i;
}
System.out.println(sum);
}
}
答案5050
题目9
求1-100之间,所有能被3整除的数字和。
public class WhileDemo02 {
public static void main(String[] args) {
int i = 1;
int sum = 0;
while (i <= 100) {
if (i % 3 == 0) {
sum = sum + i;
}
i++;
}
System.out.println(sum); }}
public class Test02 {
public static void main(String[] args) {
int sum = 0;
for (int i = 1; i <= 100; i++) {
if (i % 3 == 0) {
sum += i;
}
}
System.out.println(sum);
}
}
答案1683
题目10
统计1-100之间,既能被3整除,又能被5整除的数字,一共有多少个?
public class WhileDemo02 {
public static void main(String[] args) {
int i = 1;
int count =0;
while (i <= 100) {
if (i % 3 == 0 && i%5==0 ) {
count++;
}
i++;
}
System.out.println(count); }}
答案6
题目11:(稍难)
在中国历法中有十二生肖年份,2019年是己亥猪年,请在控制台输出从1949年(包含)到2019年(包含)中所有是猪年的年份。
参考步骤:
-
定义for循环,1949到2019的年份是循环次数.
-
对每个年份逐个判断,如果年份和2019的差值是12的倍数,说明这年是猪年.
-
打印符合条件的年份.
参考答案:
public class Test03 {
public static void main(String[] args) {
int count=0;
for (int year = 1949; year <=2019; year++) {
if ((2019-year)%12==0 ){
}
count++;
}
System.out.println(count);
}
}
答案71
题目12:(稍难)
中国使用的公历有闰年的说法,闰年的规则是:四年一闰,百年不闰,四百年再闰。(年份能够被4整除但不能被100整除算是闰年,年份能被400整除也是闰年).请打印出1988年到2019年的所有闰年年份。
参考步骤:
-
定义for循环,循环变量开始是1988,结束是2019.
-
在循环中对年份进行判断,判读条件为:可以被4整除,并且不可以被100整除,或者可以被400整除.
-
如果符合条件,输出该年份.
参考答案:
public class Test04 {
public static void main(String[] args) {
int count=0;
for (int year = 1988; year <=2019; year++) {
if ((year%4==0 && year%100!=0) || year%400==0 ){
System.out.println(year);
count++;
}
}
System.out.println("一共"+count+"个闰年");
}
}
答案
1988
1992
1996
2000
2004
2008
2012
2016
一共8个闰年