列表与LT;>环路太多

时间:2016-11-28 13:29:29

标签: c#

我的foreach循环了太多次,我不明白为什么。程序应该通过1-100并总结每个数字的四次幂。

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

3 个答案:

答案 0 :(得分:2)

您的foreach循环似乎会创建额外的循环。每次添加下一个数字时,它都会循环列表中的所有数字。

在这里,您甚至不需要foreach循环和数字列表。

public static void Main()
{
    int sum = 0;
    string temp = "";

    for (long i = 2; i < 100; i++)
    {
        temp = i.ToString();
        for(int y = 0; y < temp.Length; y++)
        {
            int digit = Convert.ToInt32(temp.Substring(y,1));
            sum += Math.Pow(digit,4);
        }
        Console.WriteLine("i = {0}, sum = {1}", i, sum);
        sum = 0;
    }
}

我不喜欢使用字符串来处理整数,下面是没有在字符串和整数之间进行转换的解决方案

public static void Main()
{
    int sum = 0;
    for (long i = 2; i < 100; i++)
    {
        for(int temp = i; temp > 0; temp /= 10)
        {
            int digit = temp % 10;
            sum += Math.Pow(digit,4);
        }
        Console.WriteLine("i = {0}, sum = {1}", i, sum);
        sum = 0;
    }
}

答案 1 :(得分:2)

让我们从头开始用相应的名称(ij?)和评论重新编写它:

 public static void Main() { 
   // we should scan numbers from 2 to 100
   for (int number = 2; number < 100; ++number) {
     string value = number.ToString();

     // digits: just the length of the string: "789" -> 3, "45" -> 2, "7" -> 1
     int digits = value.Length;

     // let's sum up the digits
     int sum = 0;

     // as we promised: sum up all 4th powers of the digits
     foreach (char c in value) {
       int digit = c - '0'; // notice, that c is character and we want int

       sum += Math.Pow(digit, 4);
     } 

     // time to output:
     Console.WriteLine("{0, 2}, sum = {1, 5}, digits count = {2, 1}",
       number, sum, digits);
   }
 }

Linq 解决方案更灵活:

int startFrom = 2;
int endAt = 100;

var result = Enumerable
  .Range(startFrom, endAt - startFrom)
  .Select(number => new {
     number = number,
     digits = number.ToString().Length,
     sum = number
       .ToString()       
       .Select(c => c - '0')
       .Sum(x => Math.Pow(x, 4)) })
  .Select(item => $"{item.number, 2}, sum = {item.sum, 5}, digits = {item.digits, 1}"); 

Console.Write(string.Join(Environment.NewLine, result));

输出:

 2, sum =    16, digits count = 1
 3, sum =    81, digits count = 1
 4, sum =   256, digits count = 1
 5, sum =   625, digits count = 1
 6, sum =  1296, digits count = 1
 7, sum =  2401, digits count = 1
 8, sum =  4096, digits count = 1
 9, sum =  6561, digits count = 1
10, sum =     1, digits count = 2
...
98, sum = 10657, digits count = 2
99, sum = 13122, digits count = 2

答案 2 :(得分:0)

另一个(部分)基于Linq的解决方案:

public static void Main()
{
    for (long i = 2; i < 100; i++)
    {
        int sum = 0;
        foreach (var digit in i.ToString().Select(digit => int.Parse(digit.ToString())))
        {
            sum += Convert.ToInt32(Math.Pow(Convert.ToInt32(digit), 4));
        }
        Console.WriteLine("i = {0}, sum = {1}", i, sum);
    }
}