java for循环练习题
时间: 2023-10-15 08:24:04 浏览: 212
以下是一些Java的for循环练习题:
输出四行直角三角形:
```java
for (int i = 0; i < 5; i++) {
for (int j = 0; j < i; j++) {
System.out.print("*");
}
System.out.println();
}
```
输出七行等腰三角形:
```java
for (int i = 0; i < 7; i++) {
for (int j = 0; j < 7; j++) {
if (j > i) System.out.print(" ");
}
for (int j = 0; j <= i; j++) {
System.out.print("*");
}
for (int j = 0; j < i; j++) {
System.out.print("*");
}
System.out.println("");
}
```
输出七行棱形:
```java
for (int a = 1; a <= 4; a++) {
for (int b = 1; b <= 4 - a; b++) {
System.out.print(" ");
}
for (int c = 1; c <= a * 2 - 1; c++) {
System.out.print("*");
}
System.out.println();
}
for (int d = 3; d >= 1; d--) {
for (int b = 1; b <= 4 - d; b++) {
System.out.print(" ");
}
for (int c = 4 - d; c <= 2 * d; c++) {
System.out.print("*");
}
System.out.println();
}
```
斐波那契数列(for循环实现):
```java
int n = 10; // 斐波那契数列的长度
int[] fib = new int[n];
fib = 0;
fib = 1;
for (int i = 2; i < n; i++) {
fib[i = fib[i - 1 + fib[i - 2];
}
for (int i = 0; i < n; i++) {
System.out.print(fib[i + " ");
}
```
正向乘法表:
```java
for (int i = 1; i <= 9; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(j + " X " + i + " = " + (i * j) + "\t");
}
System.out.println();
}
```
循环输入周一到周五的成绩,并计算平均分、最高分和最低分:
```java
Scanner input = new Scanner(System.in);
double sum = 0;
int maxScore = Integer.MIN_VALUE;
int minScore = Integer.MAX_VALUE;
for (int i = 1; i <= 5; i++) {
System.out.println("请输入周" + i + "的成绩:");
int score = input.nextInt();
while (score < 0) {
System.out.println("成绩不能为负数,请重新输入:");
score = input.nextInt();
}
sum += score;
maxScore = Math.max(maxScore, score);
minScore = Math.min(minScore, score);
}
double average = sum / 5;
System.out.println("这五个数的平均数:" + average);
System.out.println("这五个数的最高数:" + maxScore);
System.out.println("这五个数的最低数:" + minScore);
```<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [Java-for循环练习](https://blog.csdn.net/weixin_45297286/article/details/118616109)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
- *2* *3* [JAVA初学者关于for循环的十道练习题](https://blog.csdn.net/m0_62756941/article/details/132035281)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文