为什么void函数返回一个值?

编程入门 行业动态 更新时间:2024-10-14 18:20:20
本文介绍了为什么void函数返回一个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我是编程初学者,我对函数的返回值有疑问。

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函数返回一个值?

    本文发布于:2023-10-24 21:11:00,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1525018.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:函数   void

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!