开发者

Divide Array value with Array value

开发者 https://www.devze.com 2023-01-17 20:06 出处:网络
So I need to divide array value with array value. I\'m using float multi-dimensional arrays. Here is the code:

So I need to divide array value with array value. I'm using float multi-dimensional arrays.

Here is the code:

myNumbers = new float[3, 4];
float[] tempNumbers;

myNumbers[0, 0] = 3;
myNumbers[0, 1] = -6;
myNumbers[0, 2] = 3;
myNumbers[0, 3] = -12;

/*
for (int i = 0; i < 4; i++)
{
    myNumbers[0, i] = myNumbers[0, i] / myNumbers[0, 0];
}
*/

myNumbers[0, 0] = myNumbers[0, 0] / myNumbers[0, 0]; //Works (strange)
myNumbers[0, 1] = -6 / 3; // Works like this
myNumbers[0, 2] = myNumbers[0, 2] / myNumbers[0, 0]; //Does not
myNumbers[0, 3] = myNumbers[0, 3] / myNumbers[0, 0]; //Does 开发者_JAVA技巧not

Output:

1   // Worked
-2  // Worked
3   // Not so much
-12 // Not so much

It is strange to me that first value is calculated always. If I try to divide static numbers and put them in to my array it works as well. Please help me with this one. I'm posting here first time I hope you can ask questions and help here... :)

Thanks very much, stupid me. :))


since you updated the first array value already, it's always 1, hence no further division using it will change the values of the numbers myNumbers[0, 2], myNumbers[0, 3]


No, it makes perfect sense - by the time you use myNumbers[0, 0] in the third and fourth lines, that value is 1 (due to the first computation).

It may be helpful to take arrays out of the picture, as they're irrelevant here. Your code is effectively:

float a = 3;
float b = -6;
float c = 3;
float d = -12;

a = a / a;
b = -6 / 3;
c = c / a;
d = d / a;

After the first line, a is obviously 1. If you don't want earlier calculations to affect later ones, use separate variables:

float a2 = a / a;
float b2 = -6 / 3;
float c2 = c / a;
float d2 = d / a;

At this point, c2 will be 1 and d2 will be -4, which is presumably what you'd been expecting.


When this line is executed:

myNumbers[0, 0] = myNumbers[0, 0] / myNumbers[0, 0]; //Works (strange)

The result is stored at myNumbers[0,0]. So when the program executes the third line:

myNumbers[0, 2] = myNumbers[0, 2] / myNumbers[0, 0]; //Does not

The value of myNumbers[0,0] is 1, and the correct result, 3 is generated.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号