プログラム問題集

プログラム問題集

多分プログラミングの問題集でも書いていく

行列の足し算と引き算

問題

 2x2行列の足し算と引き算をするプログラムを作りましょう。

ひとつめの1行目を入力してください
>1 2
2行目を入力してください
>2 3
ふたつめの1行目を入力してください
>3 4
2行目を入力してください
>4 5

ひとつめの行列は
1 2
2 3
ふたつめの行列は
3 4
4 5

足し算の結果は
4 6
6 8
引き算の結果は
-2 -2
-2 -2
解答例

C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 行列の計算
{
    class Program
    {
        static void Main(string[] args)
        {
            Random r = new Random();
            Matrix m1 = new Matrix(2, 2);
            Matrix m2 = new Matrix(2, 2);

            //2x2行列の和
            Console.Write("ひとつめの");
            inputValue(m1);
            Console.Write("ふたつめの");
            inputValue(m2);

            Console.WriteLine();
            Console.WriteLine("ひとつめの行列は");
            m1.ShowMatrix();
            Console.WriteLine("ふたつめの行列は");
            m2.ShowMatrix();


            Console.WriteLine();
            Console.WriteLine("足し算の結果は");
            Matrix ans = m1.Plus(m2);
            ans.ShowMatrix();
            Console.WriteLine("引き算の結果は");
            ans = m1.Minus(m2);
            ans.ShowMatrix();

        }

        static void inputValue(Matrix m)
        {
            for (int i = 0; i < 2; i++)
            {
                Console.WriteLine("{0}行目を入力してください", i + 1);
                String[] s = Console.ReadLine().Split(' ');
                for (int j = 0; j < 2; j++)
                {
                    m.m[i, j] = double.Parse(s[j]);
                }
            }
        }
    }

    class Matrix
    {
        public double[,] m;

        public Matrix(int row, int col)
        {
            this.m = new double[2, 2];
            
        }

        //和
        public Matrix Plus(Matrix mat)
        {
            Matrix tm = new Matrix(m.GetLength(0), m.GetLength(1));

            for (int i = 0; i < m.GetLength(0); i++)
            {
                for (int j = 0; j < m.GetLength(1); j++)
                {
                    tm.m[i, j] = this.m[i, j] + mat.m[i, j];
                }
            }

            return tm;
        }

        //差
        public Matrix Minus(Matrix mat)
        {
            Matrix tm = new Matrix(m.GetLength(0), m.GetLength(1));

            for (int i = 0; i < m.GetLength(0); i++)
            {
                for (int j = 0; j < m.GetLength(1); j++)
                {
                    tm.m[i, j] = this.m[i, j] - mat.m[i, j];
                }
            }

            return tm;
        }

        public void ShowMatrix()
        {
            for (int i = 0; i < m.GetLength(0); i++)
            {
                Console.WriteLine("{0} {1}", m[i, 0], m[i, 1]);
            }
        }
    }
}