【问题标题】:The program doesn't run throughout the code该程序不会在整个代码中运行
【发布时间】:2014-04-12 02:43:16
【问题描述】:

使用系统; 使用 System.Collections.Generic;

namespace MATRIX_algebra
{
    public struct Struct_matrix
    {
        List<List<double>> entries; 
        public Struct_matrix(List<List<double>> values)
        {
            entries = values;
        }
    }
//    public delegate void process_matrix(Struct_matrix matrix);

    public class Matrix_init
    {
        public int size_C, size_R;


        public void matrix_size()
        {

            Console.WriteLine("Enter the size of the matrix ");
            Console.WriteLine("rows? ");
            this.size_R = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("columns? ");
            this.size_C = Convert.ToInt32(Console.ReadLine());
        }
        public List<List<double>> values = new List<List<double>>();                       
        public void matrix_value()
        {
            for (int i = 0; i < this.size_R; i++)
            {
                Console.WriteLine("Enter the entries of the {0} row  ",i+1);
                for (int j = 0; j < this.size_C; j++)
                {
                    values[i][j] = Convert.ToDouble(Console.ReadLine());
                }
            }
            Struct_matrix matrix_init = new Struct_matrix(values);
        }
    }
}        


namespace test
{   
    using MATRIX_algebra;
    public class test_values
    {
        static void Main()
        {   
            Matrix_init matrix1 = new Matrix_init();
            for (int i = 0; i < matrix1.size_R; i++)
            {
            for (int j = 0; j < matrix1.size_C; j++)
            {
                Console.WriteLine(matrix1.values[i][j]);
            }

            }

        }
    }

}

我觉得这个问题很愚蠢,但我真的需要帮助,因为我只是初学者

我不知道为什么当我运行程序时,它没有运行代码的某些部分。

我调试了一下,Main() -> 实例化Matrix_init ->public List> values = new List>(); -> 结束程序。

【问题讨论】:

  • 以后请出一个更好的标题;我们不应该打开问题来理解标题。
  • 它没有运行,因为你没有调用它。拥有方法是不够的,您需要手动调用它们。我在任何地方都看不到对 matrix_size 或 matrix_value 的任何调用,您只是在创建类。
  • 旁注:除非你明白你在做什么不要使用 struct。请检查有关“结构与类”的问题,例如stackoverflow.com/questions/1951186/…
  • @DourHighArch 虽然公平,但它确实引起了人们的兴趣

标签: c#


【解决方案1】:

你需要一个构造函数把public void matrix_size()改成:

public Matrix_init()
{
    Console.WriteLine("Enter the size of the matrix ");
    Console.WriteLine("rows? ");
    this.size_R = Convert.ToInt32(Console.ReadLine());
    Console.WriteLine("columns? ");
    this.size_C = Convert.ToInt32(Console.ReadLine());
}

这个程序正在运行只是它没有按预期工作。因为matrix_size() 方法从未被调用,所以size_Rsize_C 永远不会被分配给一个值。他们会int 的默认值为 zero,这就是为什么您的程序永远不会进入 for 循环的原因。您也可以简单地调用 matrix_size() 方法,而不是添加构造函数。

Matrix_init matrix1 = new Matrix_init();
matrix1.matrix_size();

然后调用matrix_value() 方法从用户获取输入并分配矩阵数组的值。记住所有方法都需要调用,如果你不调用它们,它们将不会做任何事情。

【讨论】:

    猜你喜欢
    • 2011-12-28
    • 2016-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 2018-12-29
    • 2015-04-11
    相关资源
    最近更新 更多