언어/JAVA
java) 자연수 1부터 시작해서 홀수를 더했을 때...
[Nada]
2019. 11. 28. 15:26
문제) 자연수 1부터 시작해서 홀수를 더했을 때 언제 1000을 넘어서고, 몇을 더할 때 1000이 넘는지 구하기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
public class ContinueBreak {
public static void main(String[] args) {
int num = 1;
int sum = 0; // 합을 0으로 초기화하는 변수
while(true) {
if(num % 2 != 0) // 홀수 찾기
sum += num; // 홀수이면 sum 에 합을 저장
if(sum>1000) {
System.out.println(num + "을 더할 때 1000을 넘는다.");
System.out.println("1000을 처음으로 넘는 수: " + sum);
break;
}
num++;
}
}
}
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
|
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs |