You need to enable JavaScript to run this app. C#选择排序程序输出全为0,如何实现程序自动生成数组元素?
优惠活动
大模型
产品
解决方案
定价
更多

C#选择排序程序输出全为0,如何实现程序自动生成数组元素?

问题原因

你运行结果全为0的核心原因是:C#中int是值类型,使用new int[f]声明数组后,所有元素会被默认初始化为0,你没有主动给数组元素赋值,所以全程操作的都是全0数组。

实现程序自动生成数组元素的方案

你可以使用C#内置的Random类生成随机整数填充数组,参考实现步骤如下:

  • 在数组声明完成后,实例化Random对象
  • 循环遍历数组,为每个索引位置赋予随机生成的整数值
  • 可以自定义随机数的上下限,比如示例里生成1到100之间的整数

修正后的完整代码

int f;
Console.WriteLine("Enter how many elements you want to be sorted:");
f = Convert.ToInt32(Console.ReadLine());
int[] myArray = new int[f];

// 新增:生成随机数填充数组
Random rand = new Random();
for (int k = 0; k < myArray.Length; k++)
{
    // 生成1~100的随机整数,你可以根据需求调整上下限参数
    myArray[k] = rand.Next(1, 101);
}

int smallest, tmp;
Console.WriteLine("\nUnsorted List");
foreach (int a in myArray)
    Console.Write(a + " ");

// 原有排序逻辑位置有误,交换操作应该放在内层循环外,否则会导致排序结果出错,这里已修正
for (int i = 0; i < myArray.Length - 1; i++)
{
    smallest = i;
    for (int j = i + 1; j < myArray.Length; j++)
    {
        if (myArray[j] < myArray[smallest])
        {
            smallest = j;
        }
    }
    // 找到当前轮次最小值再执行交换
    tmp = myArray[smallest];
    myArray[smallest] = myArray[i];
    myArray[i] = tmp;
}

Console.WriteLine("\nSorted List Using Selection Sort:");
for (int i = 0; i < myArray.Length; i++)
{
    Console.Write(myArray[i] + " ");
}
// 补充控制台暂停,方便查看输出结果
Console.ReadLine();

内容的提问来源于stack exchange,提问作者tayblinks live

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.21 05:45:03