正序、逆序
输入用空格分隔的五个整数,分别输出正序、逆序、平均值和最大值。
首先输入整数
将长度为5,即可以输入五个整数,并用空格隔开
int[] myArray = new int[5];
string[] str = Console.ReadLine().Split(' ');
输出正序
Array.Sort(myArray);
Console.Write("正序:");
for (int i = 0; i < 5; i++)
{
Console.Write(myArray[i]);
if (i != 4) Console.Write(",");
sum += myArray[i];
}
输出逆序
Array.Reverse(myArray);
Console.Write("逆序:");
for (int i = 0; i < 5; i++)
{
Console.Write(myArray[i]);
if (i != 4) Console.Write(",");
}
输出平均数
double sum = 0;
double average;
for (int i = 0; i < 5; i++)
{
sum += myArray[i];
}
average = sum / 5;
string strAverage = average.ToString("0.0");
输出最大值
int max;
Array.Sort(myArray);
max = myArray[4];
代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("请输入用空格分隔的5个整数:");
int[] myArray = new int[5];
string[] str = Console.ReadLine().Split(' ');
try
{
for (int i = 0; i < 5; i++)
{
myArray[i] = int.Parse(str[i]);
}
}
catch
{
Console.WriteLine("输入错误!");
return;
}
double sum = 0;
double average;
int max;
Array.Sort(myArray);
Console.Write("正序:");
for (int i = 0; i < 5; i++)
{
Console.Write(myArray[i]);
if (i != 4) Console.Write(",");
sum += myArray[i];
}
max = myArray[4];
average = sum / 5;
string strAverage = average.ToString("0.0");
Console.WriteLine();
Array.Reverse(myArray);
Console.Write("逆序:");
for (int i = 0; i < 5; i++)
{
Console.Write(myArray[i]);
if (i != 4) Console.Write(",");
}
Console.WriteLine();
Console.WriteLine("平均值:" + strAverage);
Console.WriteLine("最大值:" + max);
Console.ReadKey();
}
}
}
运行结果
最大值、最小值和平均值
代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp5
{
class Program
{
static void Main(string[] args)
{
double j = 1;
int[] arr = new int[100];
int sum = 0, maxl = 0, minl = 0;
Console.WriteLine("请输入数字,输入-1结束输入");
arr[0] = Int32.Parse(Console.ReadLine());
sum += arr[0];
maxl = arr[0];
minl = arr[0];
for (int i = 1; i < 100; i++)
{
arr[i] = Int32.Parse(Console.ReadLine());
if (arr[i] == -1)
{
break;
}
sum += arr[i];
maxl = Math.Max(maxl, arr[i]);
minl = Math.Min(minl, arr[i]);
++j;
}
double ave = (double)sum / j;
Console.WriteLine("最大值"+maxl);
Console.WriteLine("最小值"+minl);
Console.WriteLine("平均值"+ave);
}
}
}
结果