📄 sumandaverage.java
字号:
// Exercise 3.4
public class SumAndAverage { // saved as "SumAndAverage.java"
public static void main(String[] args){
int sum = 0; // accumulated sum
double average; // average in double
int count = 0; // set a counter to count how many numbers to add up in total
//using FOR loop
for (int i = 1; i <= 100; i++) {
sum += i;
count++;
}
//(a) using WHILE loop
/*int i = 1;
while(i <= 100){
sum += i;
i++;
count++;
}*/
//(b) compute sum and average from 111 to 8989
/*int i = 111;
while(i <= 8989){
sum += i;
i++;
count++;
}*/
// (c) sum the ODD numbers from 1 to 100
/*for (int i = 1; i <= 100; i++) {
if (i ==1 || i % 2 != 0){
sum += i;
count++;
}
}*/
// (d) sum up the integer from 1 to 100 which can be divided by 7
/*for (int i = 1; i <= 100; i++) {
if (i >= 7 && i % 7 == 0){
sum += i;
count++;
}
}*/
//compute the average using the sum divided by the number of integers
//same for all parts of this question
average = (double)sum / count;
System.out.println("The sum is " + sum);
System.out.println("The average is " + average);
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -