[英]How to Get Sum and Multiplication of Array that Entered by User in C#
我编写了这段代码来从用户那里获取数组值并显示它们。
namespace Program_2
{
class Program
{
static void Main(string[] args)
{
int[,] nums = new int[6,2];
for (int x = 0; x < 5; x++)
{
for (int y = 0; y < 2; y++)
{
Console.WriteLine("Enter Numbers");
nums[x, y] = int.Parse(Console.ReadLine());
}
}
for(int j=0; j < 5; j++)
{
for(int k = 0; k < 2; k++)
{
Console.Write(nums[j, k]+" ");
}
Console.WriteLine("");
}
Console.ReadLine();
}
}
}
但我想知道如何对用户输入的数组进行乘法和加法。
像这样“看这张图片”
和
int total = 0;
// Iterate first dimension of the array
for (int i = 0; i < nums.GetLength(0); i++)
{
// Iterate second dimension
for (int j = 0; j < nums.GetLength(1); j++)
{
total += array[i, j];
}
}
Console.WriteLine(total);
倍增
int total = 0;
// Iterate first dimension of the array
for (int i = 0; i < nums.GetLength(0); i++)
{
// Iterate second dimension
for (int j = 0; j < nums.GetLength(1); j++)
{
total *= array[i, j];
}
}
Console.WriteLine(total);
合二为一
int sum= 0;
int mul= 0;
// Iterate first dimension of the array
for (int i = 0; i < nums.GetLength(0); i++)
{
// Iterate second dimension
for (int j = 0; j < nums.GetLength(1); j++)
{
sum += array[i, j];
mul *= array[i, j];
}
}
Console.WriteLine("SUM = " + sum);
Console.WriteLine("MUL = " + mul);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.