int sum = 0;
for(int i = 0; i < numOfArrayRows; i++)
{
//Use the mod operator to find if the value is even.
if(array[i][i] % 2 == 0)
sum += array[i][i];
//Change 0's to ones
for(int j = 0; j < numOfArrayCols; j++)
if(array[i][j] == 0)
array[i][j] = 1;
}
int a[N][N] = ...;
int sum = 0;
for(int i=0; i<N; ++i)
if(a[i][i] % 2 == 0) //or a[i] & 1, if you like, just check if it's dividable by 2
sum += a[i][i];
//Your Sum
int sum = 0;
//This will iterate and grab all of the diagonals
//You don't need to iterate through every element as you only need
//the diagonals.
for(int i = 0; i < sizeOfArray; i++)
{
//This will add the value of the first, second, ... diagonal value to your sum
sum += array[i,i];
}
要将每个值设置为0到1,您可以遍历数组的每个元素并检查值是否为0,然后将该值设置为1,例如:
for(int i = 0; i < sizeOfArray; i++)
{
for(int j = 0; j < sizeOfArray; j++)
{
//Check if this value is 0;
//If it is 0, set it to 1, otherwise continue
}
}
//Read the size of the array, you can get it from .Count() if you wish
int n = Convert.ToInt32(Console.ReadLine());
int[][] a = new int[n][];
//Reading all the values and preparing the array (a)
for (int a_i = 0; a_i < n; a_i++)
{
string[] a_temp = Console.ReadLine().Split(' ');
a[a_i] = Array.ConvertAll(a_temp, Int32.Parse);
}
//performing the operation (google what diagonal matrix means)
int PrimarySum = 0, SecondarySum = 0;
for (int i = 0; i < n; i++)
{
//The If condition is to skip the odd numbers
if (a[i][i] % 2 == 0) { PrimarySum += a[i][i]; }
//For the reverse order
int lastelement = a[i].Count() - 1 - i;
if (a[i][lastelement] % 2 == 0) { SecondarySum += a[i][lastelement]; }
}
//Get the absolute value
Console.WriteLine(Math.Abs(PrimarySum - SecondarySum).ToString());
Console.ReadKey();
8条答案
按热度按时间cunj1qz11#
Diagonal表示所有x和y坐标相同的地方如果你的数组包含:
13 8 5
339 7
4 457
5 1 74
然后对角线是粗体。
wribegjk2#
假设数组是正方形:
另外,下次如果你有家庭作业的问题,请加上“家庭作业”标签:P
vxbzzdmp3#
使用二维数组非常简单,因为你不需要任何索引魔法:
这段C++代码在C或C#中应该没有太大的不同,但你应该明白这一点。同样,第二个问题也很简单:
wyyhbhjk4#
我怀疑主对角线是从坐标0,0开始的。
要将0元素替换为1,您可以执行以下操作:
if(array[i,j] == 0)array[i,j] == 1;
ie3xauqp5#
这听起来像家庭作业-但我会帮助:)
因此,如果你有一个2D数组,为了找到对角线值的总和,你将知道两个值的索引将匹配,以便为你提供每个对角线值。
要迭代这些值,您可以使用一个简单的循环来对每个对角线值求和,如图所示:
要将每个值设置为0到1,您可以遍历数组的每个元素并检查值是否为0,然后将该值设置为1,例如:
tp5buhyn6#
hvvq6cgz7#
下面是你需要的代码,没有太多解释:
dfddblmv8#
C#我会这样做
int[,] matrix = new int[4,4];