【发布时间】:2025-12-31 07:35:12
【问题描述】:
这是一个将矩阵乘以用户输入数量的代码示例。该操作应按用户输入的数量重复。例如,如果我输入数字 3,我会得到 3 个相同的打印矩阵。相反,我希望该矩阵乘以数字 3 3 次(每个新矩阵乘以数字 3)。有谁知道我该怎么做?谢谢
*using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace user_input
{
class Program
{
static void Main(string[] args)
{
string[] nodes = { "1", "2", "3", "4", "5", "6" };
int[,] adjmatrix = new int[,]
{{2,7,3,8,4},
{7,0,8,2,6},
{6,8,4,9,7},
{8,5,9,8,8},
{4,9,7,8,1}
};
int[,] newmatrix = new int[adjmatrix.GetLength(0), adjmatrix.GetLength(1)];
Printmatrix(adjmatrix, nodes, nodes, "Input Matrix");
Newline();
int n = 0;
System.Console.WriteLine("Please enter a number");
n = Convert.ToInt32(Console.ReadLine());
for (int i = 0; i < n; i++)
{
MultipliedMatrix(ref newmatrix, adjmatrix, n);
Newline();
Printmatrix(newmatrix, nodes, nodes, "Multiplied Matrix");
}
Console.ReadKey();
}
private static void Newline()
{
Console.Write("\n");
}
private static void MultipliedMatrix(ref int[,] newmatrix, int[,] adjmatrix, int n)
{
for (int i = 0; i < adjmatrix.GetLength(0); i++)
{
for (int j = 0; j < adjmatrix.GetLength(1); j++)
{
newmatrix[i, j] = adjmatrix[i, j] * n;
}
}
}
private static void Printmatrix(int[,] adjmatrix, string[] nodes_h, string[] nodes_v, string title)
{
if (adjmatrix.GetLength(0) != 0)
{
Console.ForegroundColor = ConsoleColor.White;
Console.Write("{0}\n", title);
Console.ForegroundColor = ConsoleColor.DarkGreen;
Console.Write("\t");
for (int i = 0; i < adjmatrix.GetLength(0); i++)
Console.Write("{0}\t", nodes_v[i]);
for (int i = 0; i < adjmatrix.GetLength(0); i++)
{
Newline();
Console.ForegroundColor = ConsoleColor.DarkGreen;
Console.Write("{0}\t", nodes_h[i]);
for (int j = 0; j < adjmatrix.GetLength(1); j++)
{
Console.ForegroundColor = ConsoleColor.DarkGray;
if (adjmatrix[i, j] < 500) Console.Write("{0}\t", adjmatrix[i, j]);
else
{
Console.ForegroundColor = ConsoleColor.Red;
Console.Write("-\t", adjmatrix[i, j]);
}
}
Console.ForegroundColor = ConsoleColor.White;
}
Newline();
}
}
}
}*
*
【问题讨论】:
标签: c# multidimensional-array visual-studio-2015 user-input