gpt4 book ai didi

java - 将两个数组合并为一个交替元素?

转载 作者:行者123 更新时间:2023-12-01 21:50:53 32 4
gpt4 key购买 nike

我一直在尝试用以下算法解决这个问题,但它不起作用。

import java.util.Scanner;
import java.lang.Math;

public class AlterConcatenateArrays {
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
System.out.println("How many elements do you want the first array have?");
int N = s.nextInt();
s.nextLine();
System.out.println("How many elements do you want the second array have?");
int M = s.nextInt();
int[] a = new int[N];
int[] b = new int[M];
System.out.println("The elements of the first array are: ");
for (int i = 0; i < N; i++) {
a[i] = (int) (Math.random() * 20);
System.out.print(a[i] + " \n");
}
System.out.println("The elements of the second array are: ");
for (int i = 0; i < M; i++) {
b[i] = (int) (Math.random() * 20);
System.out.print(b[i] + " \n");
}
System.out.println("Now we are going to concatenate the arrays by alternatingly choosing");
int[] c = new int[N + M];
for (int i = 0; i < ((N + M) / 2); i++) {
a[i] = c[2 * i + 0];
b[i] = c[2 * i + 1];
}
System.out.println("The new array is: ");
for (int i = 0; i < N + M; i++) {
System.out.print(c[i] + "\t");
}
}
}

该程序的输出是这样的:

How many elements do you want the first array have?
2
How many elements do you want the second array have?
3
The elements of the first array are:
17
18
The elements of the second array are:
6
14
15
Now we are going to concatenate the arrays by alternatingly choosing
The new array is:
0 0 0 0 0

最佳答案

您已在此处交换了作业。

{
a[i] = c[2*i+0];
b[i] = c[2*i+1];
}

应该从ab分配到c,就像

{
c[2*i+0] = a[i];
c[2*i+1] = b[i];
}

关于java - 将两个数组合并为一个交替元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35256734/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com