如何递归计数直到小于 n。

huangapple go评论86阅读模式
英文:

How do I recursively count up to less than n

问题

我在处理循环和数组的应用问题时遇到困难。

我有一个变量 "n" 代表循环的限制,即

如果 n = 3,则数组看起来像:

arr[1,2,3,1,2,3,1,2,3];

或者如果 n = 4,则它看起来像:

arr[1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4];

以下是我的代码,有人请告诉我在实现上述问题时犯了什么错误...

public static void main(String[] args) {
    
    countingUp(3);

}

public static void countingUp(int n) {
    int[] arr = new int[n * n];
    int k = n;
    for(int i = 0; i < n; i++) {
        for(int j = 0; j < n; j++) {
            arr[i] = n ;
        }
    }
    
    System.out.println(Arrays.toString(arr));
}

请检查你的代码,你在循环中没有正确更新数组元素的值。

英文:

I am struggling with the problem of having applications of loops and arrays.

I have a variable "n" which represents the limit of the loop, i.e.

if n = 3, the array would look like:

arr[1,2,3,1,2,3,1,2,3];

or if n = 4, it would look like:

arr[1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4];

here's my code so far, someone please let me know the mistake I have made in implementing the above problem...

public static void main(String[] args) {
	
	countingUp(3);

}

public static void countingUp(int n) {
	int[] arr = new int[n * n];
	int k = n;
	for(int i = 0; i &lt; n; i++) {
		for(int j = 0; j &lt; n; j++) {
			arr[i] = n ;
		}
	}
	
	System.out.println(Arrays.toString(arr));
}

答案1

得分: 1

This is the major mistake you have done...

>arr[i] = n ;

You should update value after each interval of length n which can be controlled by the loop running with i and the value inside each interval could be controlled with the loop j. See that one change I have made in the code below...

这是你犯的主要错误...

>arr[i] = n;

在每个长度为n的间隔之后,您应该更新值,这可以由运行i的循环控制,每个间隔内的值可以由循环j控制。请看下面代码中我所做的一项更改...

public static void main(String[] args) {

countingUp(3);

}

public static void countingUp(int n) {
int[] arr = new int[n * n];
int k = n;
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
arr[i*n+j] = j+1 ;
}
}

System.out.println(Arrays.toString(arr));

}

英文:

This is the major mistake you have done...

>arr[i] = n ;

You should update value after each interval of length n which can be controlled by the loop running with i and the value inside each interval could be controlled with the loop j. See that one change I have made in the code below...

public static void main(String[] args) {
    
    countingUp(3);

}

public static void countingUp(int n) {
    int[] arr = new int[n * n];
    int k = n;
    for(int i = 0; i &lt; n; i++) {
        for(int j = 0; j &lt; n; j++) {
            arr[i*n+j] = j+1 ;
        }
    }
    
    System.out.println(Arrays.toString(arr));
}

huangapple
  • 本文由 发表于 2020年8月2日 21:18:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/63216458.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定