我的foreach循環太多次了,我不明白爲什麼。該方案應該低谷1-100,並總結每個數字的四次方。List <>太多循環
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
int sum = 0;
string temp = "";
List<int> digits = new List<int>();
for (long i = 2; i < 100; i++)
{
temp = i.ToString();
for(int y = 0; y < temp.Length; y++)
{
digits.Add(Convert.ToInt32(temp.Substring(y,1)));
foreach(int j in digits)
{
sum += Convert.ToInt32(Math.Pow(j,4));
Console.WriteLine("foreach loop: i = {0}, y = {1}, sum = {2}, j = {3}, digits count = {4}",i,y,sum,j,digits.Count);
}
}
Console.WriteLine("i = {0}, sum = {1}", i, sum);
sum = 0;
digits.Clear();
}
}
}
下面是輸出例如
foreach loop: i = 10, y = 0, sum = 1, j = 1, digits count = 1
foreach loop: i = 10, y = 1, sum = 2, j = 1, digits count = 2
foreach loop: i = 10, y = 1, sum = 2, j = 0, digits count = 2
i = 10, sum = 2
foreach loop: i = 11, y = 0, sum = 1, j = 1, digits count = 1
foreach loop: i = 11, y = 1, sum = 2, j = 1, digits count = 2
foreach loop: i = 11, y = 1, sum = 3, j = 1, digits count = 2
i = 11, sum = 3
foreach loop: i = 12, y = 0, sum = 1, j = 1, digits count = 1
foreach loop: i = 12, y = 1, sum = 2, j = 1, digits count = 2
foreach loop: i = 12, y = 1, sum = 18, j = 2, digits count = 2
i = 12, sum = 18
爲什麼foreach循環上的2位的數字3次?在迴路後清除數字列表
讓我們以10爲例。
temp = "10";
temp.Length = 2;
second for loop (y) runs twice. 1 < 2
digits gets filled twice
foreach runs three times
然後好像你所有環路位數每個數字在列表中。兩個數字=加一個數字時一個循環,然後再加兩個數字時循環兩次,因爲列表中包含兩個數字 – Fabio
這是因爲你有一個超過數字的循環for(int y = 0; y
juharr
您需要在第二個'for'循環之外移動'foreach'循環。 – Fabio