随机生成10个小于100的整数,并放入一维数组中存放,编程求其中小于80且大于9的书的平均数,保留两位小数
#include <stdio.h>
#include <iostream>
#include <time.h>
int main()
{
srand((unsigned)time(NULL));
int num[10] = { 0 }, sum = 0,count=0;
for (int i = 0; i < 10; i++)
{
num[i] = rand() % 100;
if (num[i] > 9 && num[i] < 80) {
sum += num[i];
printf("%d ", num[i]);
count += 1;
}
}
printf("\n平均数为:%.2f\n", 1.0 * sum / count);
system("pause");
return 0;
}
代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace random
{
class Program
{
static void Main(string[] args)
{
Random r = new Random();
int[] a = new int[10];
Console.WriteLine("随机产生的原数组:");
for(int i=0;i<a.Length;i++)
{
a[i] = r.Next(1, 100);
Console.Write(a[i] + " ");
}
Console.WriteLine();
//升序
Array.Sort(a);
Console.WriteLine("升序后的数组:");
for(int j=0;j<a.Length;j++)
{
Console.Write(a[j] + " ");
}
Console.WriteLine();
//反转(将升序反转过后就是降序)
Array.Reverse(a);
Console.WriteLine("(反转)降序后的数组:");
for (int n = 0; n < a.Length; n++)
{
Console.Write(a[n] + " ");
}
Console.ReadKey();
}
}
}
Random rand = new Random(DateTime.Now.Millisecond);
var result = Enumerable.Range(1, 10).Select(p => rand.Next(0, 100)).Where(p => p > 9 && p < 80).Average();
Console.WriteLine(result.ToString("N2"));