c# - 如何找到数组的最小值和最大值以及数组的平方和反转的数组?
问题描述
我正在尝试编写一个代码,该代码将为我提供数组中的最高和最低数字以及数组平方和反转数组。当我运行程序时,我一直得到 0,但没有其他问题,所以设置为错误,但我无法弄清楚是什么问题,因为没有错误消息。这是代码:
using System;
namespace ArrayMethods
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter an array size: ");
int someArray = Convert.ToInt32(Console.ReadLine());
int[] Array = new int[someArray];
String input = Console.ReadLine();
int[] arrayPart3 = new int[10];
ReversedArray(arrayPart3);
for (int index = 0; index < arrayPart3.Length; index++)
{
Console.Write(arrayPart3[index] + "| ");
}
Console.WriteLine();
Console.WriteLine("Largest is:" + ArrayMax(arrayPart3));
Console.WriteLine("Smallest is:" + ArrayMin(arrayPart3));
SquaredArray(arrayPart3);
for (int index = 0; index<arrayPart3.Length; index++)
{
Console.Write(arrayPart3[index] + "| ");
}
Console.WriteLine();
ReversedArray(arrayPart3);
for (int index = 0; index < arrayPart3.Length; index++)
{
Console.Write(arrayPart3[index] + "| ");
}
}
public static int ArrayMax(int[] someArray)
{
int highest = someArray[0];
for (int index = 0; index < someArray.Length; index++)
{
if (someArray[index] > highest)
highest = someArray[index];
}
return highest;
}
public static int ArrayMin(int[] someArray)
{
int lowest = someArray[0];
for (int index = 0; index < someArray.Length; index++)
{
if (someArray[index] < lowest)
lowest = someArray[index];
}
return lowest;
}
public static void SquaredArray(int[]someArray)
{
for (int index = 0; index < someArray.Length; index++)
{
someArray[index] = someArray[index] * someArray[index];
}
}
public static void ReversedArray(int[] someArray)
{
for (int index = 0; index<someArray.Length; index++)
{
int temp = someArray[index];
someArray[index] = someArray[someArray.Length - 1 - index];
someArray[someArray.Length - 1 -index] = temp;
}
}
}
}
解决方案
缺少解析输入的代码
这是一个基于 linq 的紧凑代码:
using System;
using System.Linq;
public class Program
{
public static void Main()
{
var input = Console.ReadLine();
// or use a fixed input: var input = "1 2 3 4";
int[] arrayPart3 = input.Split(' ',',', ';').Select(s => int.Parse(s)).ToArray();
Console.WriteLine("Reversed: " + string.Join("| ", arrayPart3.Reverse()));
Console.WriteLine();
Console.WriteLine("Largest is:" + arrayPart3.Max());
Console.WriteLine("Smallest is:" + arrayPart3.Min());
Console.WriteLine("Squared: " + string.Join("| ", arrayPart3.Select(i => i*i)));
Console.WriteLine("Reversed Squared: " + string.Join("| ", arrayPart3.Reverse().Select(i => i*i)));
}
}
推荐阅读
- python - Python3如何检查一个项目是否已经在txt文件中
- ios - flutter:连接Linux开发机和远程Xcode进行构建和iOS模拟器
- php - 有没有更好的方法在使用 PHP 的 Bootstrap CSS 中每隔 3 行打破列?等宽多行
- c++ - std::normal_distribution 的性能问题?
- c# - Assembly.LoadFrom 有效,Assembly.Load 无效
- jenkins - Jenkins - 错误消息 431 原因:请求标头字段太大
- c# - 在 Xamarin.Android 使用的 NuGet 包中包含本机库
- javascript - [Vue 警告]:使用带有参数的 mixin 时无法挂载组件
- android - 将触摸事件从对话框片段传递到正下方的视图(在父活动内)
- google-apps-script - 在 Google 表格上的脚本中从右到左对齐希伯来语文本