[英]Sum of selected values in an int Array in c#
我正在學習如何使用 c# 進行編程。 我真的很陌生。 我的問題是我正在嘗試創建一個顯示 10 個數字的數組。 我希望我的代碼檢查 10 以下的哪些數字可以被 3 或 5 整除並求和。 我嘗試使用 .Sum() 函數,但表示 int 不包含 Sum 的定義。 我已經在我的程序中使用了 System.Linq。 有誰知道如何使這筆款項發生?
{
int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int sum = 1 + 2;
foreach (int n in numbers)
{
if (n % 3 == 0 || n % 5 == 0)
{
int total = n.Sum();
Console.WriteLine(total);
}
else
{
Console.WriteLine("not divisible");
}
}`
所以你的問題是你試圖在一個int
類型的變量n
上調用.Sum()
(你在這里定義它: foreach (int n in numbers)
,這不是一個方法。
使用 LINQ,您可以執行以下操作:
var numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
var total = numbers.Where(n => n % 3 == 0 || n % 5 == 0).Sum();
每個人都忘記了數組應該包含 10 個數字,但有些數字值可能大於 10。只應檢查小於 10 的數字值。 所以正確答案應該是
var numbers = new int[] { 1, 9, 5, 6, 8, 10,4, 15, 25, 3};
var total = numbers.Where( n => (n<10) && ( n % 3 == 0 || n % 5 == 0)).Sum();
如果我理解正確並使用您的代碼,這就是您想要的。
int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int sum = 1 + 2;
int total=0;
foreach (int n in numbers)
{
if (n % 3 == 0 || n % 5 == 0)
{
int total += n;
}
else
{
Console.WriteLine("not divisible");
}
}
Console.WriteLine(total);
我將打印移到 foreach 之后,以便在完成后得到一個結果
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.