我必须用奇数的范围(这里是n
)填充一个数组:1,3,5,7,9 ......但是每个奇数和我之间总是有一个0不明白为什么。用奇数填充数组
注:评论信件是由我们的教授给出的资本项目下的代码...
下面是代码:
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
您可以张贴输出吗? – dsharew
是的,我当然会这样做 – algorithmic
你的教授通过让你在for循环之外声明'i'给你不好的建议 –