帕斯卡的三角代码导致无限循环

问题描述 投票:0回答:1

标题

我正在尝试用 C# 编写帕斯卡三角形,但我无法理解代码有什么问题,

这是我写的:

static void Main(string[] args)
{
    int numrows = int.Parse(Console.ReadLine());
    PascalsTriangle(numrows);
}
static void PascalsTriangle(int numRows)
{
    List<int> triangle = new List<int>();
    List<int> trianglestorage = new List<int>();
    Console.WriteLine("   " + string.Join("", triangle));
    for (int i = 0; i < numRows; i++)
    {
        Console.WriteLine();
        triangle.Add(1);
        triangle.Insert(0, 1);
        Console.WriteLine(string.Join(", ", triangle)); // this is the last normal output and the system shows memory overflow error inside the loop. for some reason it goes on forever even though triangle.Count is now 3 and it should repeat only twice 
        for (int j = 0; j < triangle.Count() - 1; j++)
        {
            trianglestorage.Add(triangle[j] + triangle[j+1]);
        }
        triangle = trianglestorage;
    }

}

目前输出如下:

1

1, 1

1,2,1

然后程序继续运行而不输出任何内容,最终由于内存溢出而关闭

c# console-application
1个回答
0
投票

代码有一些变化。

using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;

namespace console_test
{
    class Program
    {
        static void Main(string[] args)
        {
            int numrows = int.Parse(Console.ReadLine());
            PascalsTriangle(numrows);
        }

        static void PascalsTriangle(int numRows)
        {
            string[] lines = new string[numRows];
            string[] previous_lines = new string[numRows];
            for (int i = 0; i < numRows; i++)
            {
                lines = new string[i + 1];
                lines[0] = "1"; lines[lines.Length - 1] = "1";
                for (int j = 0; j < i - 1; j++)
                {
                    lines[j + 1] = (int.Parse(previous_lines[j]) + int.Parse(previous_lines[j + 1])).ToString(); 
                }
                previous_lines = lines;
                Console.WriteLine(string.Join(",", lines));
            }

            Console.ReadKey();
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.