为什么void函数返回一个值? [英] Why does a void function return a value?
问题描述
我是编程初学者,我对函数的返回值有疑问。
I'm a programming beginner and I have question regarding a return value from a function.
我正在学习Java。
我附上了我的书中的代码,其中包含经典的选择排序。
I have attached code from my book that features a classic Selection Sort.
现在很明显,这本书中的代码可以运行。但是,主要功能中的这三行是我的问题的基础:
Now obviously the code from the book works. However, these three lines in main function are the basis of my question:
-
int [] a = new int [] { 1,9,2,8,3,7,4,6,5};
int []a=new int[]{1,9,2,8,3,7,4,6,5};
sort(a);
if(ascending(a))System.out.println(Works);
if(ascending(a)) System.out.println("Works");
所以我的问题是:
在第2行,如何检索已排序的a [] if sort()函数是否为空?
该行不应该是:a = sort(a)?
public class SelectionSort
{
public static void main(String[]args)
{
int []a=new int[]{1,9,2,8,3,7,4,6,5};
sort(a);
if(ascending(a)) System.out.println("Virðist virka");
else System.out.println("Virkarekki");
}
public static void sort(int[]a)
{
if(a.length<2) return;
int i=0;
while(i!=a.length)
{
int k=i+1;
while(k!=a.length)
{
if(a[k]<a[i])
{
int tmp=a[i];
a[i]=a[k];
a[k]=tmp;
}
k++;
}
i++;
}
}
public static boolean ascending(int[]a)
{
if(a.length<2) return true;
int i=1;
while(i!=a.length)
{
if(a[i-1]>a[i]) return false;
i++;
}
return true;
}
}
推荐答案
自数组是对象,它们通过引用传递(它们在内存中的位置),因此 sort()
中的更改为 a []
还更改在main中声明的 a []
。所以a在函数内被改变了。但是,你不能说
Since arrays are objects, they are passed by their reference (their location in memory), so the changes within sort()
to a[]
also change a[]
declared in main. So a is changed within the function. However, you cannot say
public static void change(int[] a) {
a = new int[3];
a = {1, 2};
}
这不会改变 a
本身,因为它只是创建一个参数 a
指向的新内存位置,而不更改参数。
That will not change a
itself, because that just makes a new memory location that the parameter a
points to, without changing the parameter.
这篇关于为什么void函数返回一个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!