【C#】正序、逆序、最大值、最小值和平均值
【摘要】 正序、逆序输入用空格分隔的五个整数,分别输出正序、逆序、平均值和最大值。首先输入整数将长度为5,即可以输入五个整数,并用空格隔开int[] myArray = new int[5]; string[] str =Console.ReadLine().Split(’ ');输出正序Array.Sort(myArray);Console.Write(“正序:”);for (int i = 0...
正序、逆序
输入用空格分隔的五个整数,分别输出正序、逆序、平均值和最大值。
首先输入整数
将长度为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);
}
}
}
结果
【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)