新・明解 Java 入門 演習 4-13, 4-14, 4-15 解答
Hello, Terminal!swaponQです!
前回に引き続き、今回は演習 4-13, 4-14, 4-15 に取り組んでいこうと思います。
- 演習 4-13
1からnまでの和をを求めるList4-10をfor文で実現せよ。
ex04_13.java
import java.util.Scanner;
class ex04_13 {
public static void main(String[] args) {
Scanner stdIn = new Scanner(System.in);
System.out.println("1からnまでの和を求めます。");
int n;
do {
System.out.print("nの値:");
n = stdIn.nextInt();
} while (n <= 0);
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += i;
}
System.out.println("1から" + n + "までの和は" + sum + "です。");
}
}実行結果
1からnまでの和を求めます。 nの値:5 1から5までの和は15です
- 演習 4-14
演習4-13を書きかえて、右のように式を表示するプログラムを作成せよ。
ex04_14.java
import java.util.Scanner;
class ex04_14 {
public static void main(String[] args) {
Scanner stdIn = new Scanner(System.in);
int n;
do {
System.out.print("nの値:");
n = stdIn.nextInt();
} while (n <= 0);
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += i;
System.out.print(i);
System.out.print(i == n ? " = " : " + ");
}
System.out.println(sum);
}
}実行結果
nの値:5 1 + 2 + 3 + 4 + 5 = 15
- 演習 4-15
身長と標準体重の対応表を表示するプログラムを作成せよ。
表示する身長の範囲(開始値/終了値/増分)整数値として読み込むこと。
※標準体重は(身長 - 100)× 0.9によって求められる。
ex04_15.java
import java.util.Scanner;
class ex04_15 {
public static void main(String[] args) {
Scanner stdIn = new Scanner(System.in);
int start;
int end;
int display;
do {
System.out.print("何cmから:");
start = stdIn.nextInt();
System.out.print("何cmまで:");
end = stdIn.nextInt();
System.out.print("何cmごと:");
display = stdIn.nextInt();
} while (start <= 100 || end <= 100 || display <= 0);
System.out.println("身長 標準体重");
for (int i = start; i <= end; i += display) {
System.out.println(i + " " + (i - 100) * 0.9);
}
}
}実行結果
何cmから:150 何cmまで:190 何cmごと:5 身長 標準体重 150 45.0 155 49.5 160 54.0 165 58.5 170 63.0 175 67.5 180 72.0 185 76.5 190 81.0
今回は以上です。お疲れ様でした!
次回は演習 4-16, 4-17, 4-18 です。
Goodbye, Terminal… swaponQでした!