C#初学者。我熟悉Python,在Python中,(我认为)你会做这样的事情:
myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def SumOfEvens(myList):
#Initialize the results variable.
result = 0
#Loop through each element of the list.
for i in myList:
#Test for even numbers.
if not i % 2:
result += i
return(result)
print SumOfEvens(myList)
30
我试图在C#中重新创建它,除了我需要编写静态方法然后在Main
到目前为止,这就是我所拥有的:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Strings
{
class Program
{
static void SumofEvens(string[] args)
{
//initialize results variable
int result = 0
//check if the number is even. If it's even, add it.
foreach (int i in l)
if (i % 2 == 0)
{
int result += i
}
}
static void Main(string[] args)
{
l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
return SumofEvens(l);
}
}
}
首先,我不知道如何在main中正确创建列表l
。这样做的正确方法是什么?
int[] l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
然后我需要将Main
的结果写入控制台。那会是
Console.WriteLine(Main);
Console.ReadLine();
我的代码的最底部是哪里?目前,只是告诉控制台说"输入一个整数"。谢谢你的帮助。
答案 0 :(得分:4)
var l =new List<int> {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
var result = l.Where(i=>i%2==0).Sum();
答案 1 :(得分:2)
创建数组可以通过以下方式完成:
int[] l = {1,2,3,4,5,6,7,8,9,10};
或者,如果您在范围内创建数组:
int[] l = Enumerable.Range(1, 10).ToArray();
您需要在上面添加System.linq
。写入控制台将是
Console.WriteLine(result);
但是你不会在main中返回一个值,因为你将它定义为void,你可以调用你的方法并在静态方法中打印结果或者通过返回结果在main中打印结果:
static int SumofEvens(string[] args)
{
...
// either print in method, the above return would be void
Console.WriteLine(result);
// or return result, the above return would be int as shown
return result;
}
// if SumofEvens returns int, in main ...
Console.WriteLine(SumofEvens());
答案 2 :(得分:1)
以下是您的工作方式:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Strings
{
class Program
{
// method SumOfEvens take an int array and returns an int
static int SumOfEvens(int[] integers)
{
//initialize results variable
int result = 0
//check if the number is even. If it's even, add it.
foreach (int i in integers)
if (i % 2 == 0)
{
int result += i
}
// You should return the result
return result;
}
static void Main(string[] args)
{
// that's how you create an array of integers in c#
int[] integers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// store the sum in a variable
int result = SumOfEvens(integers);
// write result to the console
Console.WriteLine("The sum of even integers is: "+ result);
// never return something in the Main method
// because it returns void (nothing)
}
}
}
答案 3 :(得分:0)
使用linq的直接方法
using System.Linq;
static int SumofEvens(int[] Arr)
{
return Arr.Where(number=>number%2==0).Sum();
}