用奇数填充数组
我必须用奇数的范围(这里是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
对于每个偶数索引,您都得到0
,因为该索引处的值从不设置。
这条线:
int[] t = new int[n];
声明长度n
的INT,其中每个元素被初始化为0的数组现在考虑您的代码:
for (i = 0; i < t.length; i++) {
if (i % 2 != 0) {
t[i] += i;
}
}
你的意思是:当索引我的数组很奇怪,让我们把它设置为这个索引,否则,什么都不做(并且保持0)。这解释了你得到的结果。
你想要做的不是检查数组的索引是否是奇数:你想为数组的每个索引设置一个奇数值。考虑下面的代码来代替:
for (i = 0; i < t.length; i++) {
t[i] = 2 * i + 1;
}
对于每个索引,这个阵列的值设置为奇数(2n+1
总是单数)。
(请注意,我写=
而不是+=
:它给人的意图更好,不依赖于一个事实,即阵列初始化为0)
非常感谢您的快速解答! :)我现在明白了我的错误 – algorithmic
试试这个相反:
int odd = 1;
for (int i = 0; i < t.length; i++) {
t[i] = odd;
odd += 2;
}
问题是这样的:
int[] t = new int[n];
将创建一个填充零的数组。在你的for循环中,你设置了奇数,所以其他的都保持为零。
感谢你的帮助! – algorithmic
使用Java 8,IntStream很简单:
IntStream.range(0, n).filter(element -> element % 2 != 0)
.forEach(System.out::println);
用法:
public class F5B1 {
public static java.util.Scanner scanner = new java.util.Scanner(System.in);
public static void main(String[] args) {
System.out.print("Entrez n : ");
int n = scanner.nextInt();
IntStream.range(0, n).filter(element -> element % 2 != 0)
.forEach(System.out::println);
}
}
谢谢,我学到了一些新东西! ,我从来没有听说过那 – algorithmic
问题是,答案重写教授代码的一部分。 – Tunaki
您可以张贴输出吗? – dsharew
是的,我当然会这样做 – algorithmic
你的教授通过让你在for循环之外声明'i'给你不好的建议 –