【发布时间】:2015-10-17 09:04:53
【问题描述】:
我必须用奇数范围(此处为n)填充一个数组:1,3,5,7,9...但我总是在每个奇数之间有一个 0,我不明白为什么。
注:cmets中大写字母下的代码是我们教授给的……
代码如下:
public class F5B1 {
public static java.util.Scanner scanner = new java.util.Scanner(System.in);
public static void main(String[] args) {
// Creation of Array : DON'T CHANGE THIS PART OF THE PROGRAM.
System.out.print("Entrez n : ");
int n = scanner.nextInt();
int[] t = new int[n];
int i;
// fill the array : PART OF THE PROGRAM TO FULFILL
// INSTRUCTIONS :
// ADD NO ADDITIONAL VARIABLES
// DON'T USE ANY OF THE MATH METHODS
// DON'T ADD ANY METHODS
// I wrote this piece of code
for (i = 0; i < t.length; i++) {
if (i % 2 != 0) {
t[i] += i;
}
}
// display of the array : DON'T CHANGE THIS PART OF THE PROGRAM
System.out.println("Those are the odd numbers : ");
for (i = 0; i < t.length; i++) {
System.out.println(t[i]);
}
}
}
输出:
Enter n : 10
Those are the odd numbers :
0
1
0
3
0
5
0
7
0
9
【问题讨论】:
-
你也可以发布输出吗?
-
是的,我当然会这样做
-
你的教授让你在 for 循环外声明
i是在给你不好的建议
标签: java