微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用随机数 80-100 填充数组并使用以数组为参数的方法打印两种不同的方式

如何解决使用随机数 80-100 填充数组并使用以数组为参数的方法打印两种不同的方式

我试图让两个数组包含 80-100 之间的 20 个随机值,但看起来它只是打印 system.int32[]。它应该在 FillArray 方法中附加值,但我认为它不起作用。我可能已经盯着这个看得太久了,但我哪里出错了?

using System;

class MainClass {
    public static void Main(string[] args) {
        int[] student1 = new int[20];
        int[] student2 = new int[20];
        FillArray(student1);
        FillArray(student2);

        Console.WriteLine("---------- Unsorted ----------");
        displayOutput(student1,student2);

        Sort2Arrays(student1,student2);

        Console.WriteLine("---------- Sorted ----------");
        displayOutput(student1,student2);

        Console.WriteLine("done");

    } //end main
    public static void FillArray(int[] xArray) {
        Random rnd = new Random();
        for (int i = 0; i < xArray.Length; i++) {
            xArray[i] = rnd.Next(80,101);
        } //end for
    }

    public static void Sort2Arrays(int[] xArray,int[] yArray) {
        Array.sort(xArray);
        Array.sort(yArray);
    }

    public static void displayOutput(int[] xArray,int[] yArray) {
        foreach(int val in xArray) {
            Console.WriteLine("{0}-{1}",xArray,yArray);
        } //end foreach
    } //end display
} //end class

解决方法

DisplayOutput 方法是错误的,所以我用

替换了它
public static void DisplayOutput(int[] xArray,int[] yArray) {
    for (int i = 0; i < 20; i++) {
        Console.WriteLine("{0}-{1}",xArray.GetValue(i),yArray.GetValue(i));
    } 
}

它应该可以正常工作

,

你应该改变你的 for 循环,现在你打印你的数组本身,你应该打印数组的元素:

public static void DisplayOutput(int[] xArray,int[] yArray) {
    for (var i = 0; i < xArray.Length; i++) {
        Console.WriteLine("{0}-{1}",xArray[i],yArray[i]);
    }
}

我使用了 for 循环,因为您应该打印两个数组的元素。

P.S 只有当这些数组具有相同数量的元素时,此 for 循环才是正确的。

更新

或者如果你想使用 foreach 循环,你可以这样写:

public static void DisplayOutput(int[] xArray,int[] yArray) {
    var arrays = xArray.Zip(yArray,(i,j) = >new {
        x = i,y = j
    });
    foreach(var v in arrays) {
        Console.WriteLine("{0}-{1}",v.x,v.y);
    }
}

使用Enumerable.Zip

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。