我必须找到一组数字的平均值... [英] I have to find the average of a set of numeros...

查看:86
本文介绍了我必须找到一组数字的平均值...的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须找到一组numeros的平均值.Como我将平均值舍入小数点后的小数点后两位。什么是代码?

推荐答案

Hola Reinaldo;



我们都必须开始某处。这应该可以帮到你:



Hola Reinaldo;

We all have to start somewhere. This should get you started:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    double sum = 0.0;

    for (int i = 1; i < argc; i++)
    {
        sum += strtod(argv[i]);
    }

    argc--;

    printf("%0.2f\n", sum / argc);

    return 0;
}


你的问题包括C#作为标签,所以我会说解决方案。



如果您使用的是C#和.NET Framework v3.5或更高版本,则以下内容将起作用:

Your question included C# as a tag so I'll speak to that solution.

If you're using C# and the .NET Framework v3.5 or later the following will work:
var numbers = new List<int>() { 3, 9, 25, 34, 18, 53, 12, 15 };

// Get the average
double rawAverage = numbers.Average();

// Get the rounded average
double roundedAverage = Math.Round( rawAverage, 2, MidpointRounding.AwayFromZero );

Console.WriteLine( rawAverage );
Console.WriteLine( roundedAverage );





如果您使用的是C#和早期版本的.NET Framework然后这将起作用:



If you're using the C# and an earlier version of the .NET Framework then this will work:

var numbers = new List<int>() { 3, 9, 25, 34, 18, 53, 12, 15 };

// Get Total of all numbers
int total = 0;
foreach( var number in numbers )
{
    total += number;
}

// Get the average
double rawAverage = (double) total / numbers.Count;

// Get the rounded average
double roundedAverage = Math.Round( rawAverage, 2, MidpointRounding.AwayFromZero );

Console.WriteLine( rawAverage );
Console.WriteLine( roundedAverage );





两个代码片段将产生21.125的原始平均值和舍入的平均值21.13。如果你想使用银行家的舍入,只需省略MidpointRounding.AwayFromZero参数,舍入的值将是21.12。



Both code snippets will produce a raw average value of 21.125 and a rounded average value of 21.13. If you want to use banker's rounding just omit the MidpointRounding.AwayFromZero parameter and the rounded value will be 21.12 instead.


这篇关于我必须找到一组数字的平均值...的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆