简体   繁体   中英

Sum of absolute numbers in function

I try this:

public static int sum(List<int> list)
{
        int sum = 0;

        foreach (var item in list)
        {
            sum = item + sum;
        }

        return sum;
}

public static int sumAbsolute(List<int> list)
{
        foreach (var item in list)
        {
            Math.Abs(item);
        }          

        return sum(list); 
}

and the in the main function:

static void Main(string[] args)
{          
        var list = new List<int>() {
            -1,-2,-3
        }; 

        Console.WriteLine(sumAbsolute(list));
        Console.ReadKey();
}

But the output is -6 and not 6.

So why doesn't my code work?

In short: because Math.Abs(item) returns an int that you dont use:

You could do:

for(int i = 0; i < list.Length; i++)
{
    list[i] = Math.Abs(list[i]);
} 

or with LINQ:

public static int SumAbsolute(IEnumerable<int> list)
{
    return list.Select(Math.Abs).Sum();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM