简体   繁体   中英

multiply two negative numbers in c++

when I tried to multiple two negative numbers the value it is zero in c++, for example -5 * -3 the result is zero, why? this is my code

  #include <bits/stdc++.h>
      #include <iostream>

   using namespace std;
     void Multiply(const int v_arr[], const int m_arr[][3], int signed 
  o_arr[], int size)

{

for (int i = 0; i < size; i++) {
    for (int j = 0; j < size; j++) {
        o_arr[i] = 0;
        for (int k = 0; k < 3; k++)
            o_arr[i] += v_arr[k] * m_arr[k][i];
    }
}

//End your code here
    }
    int main()
     {
  int n;
   cin >> n;
int v_array[n];
int m_array[n][3];
int signed o_array[3];
for (int i = 0; i < n; i++) {
    cin >> v_array[i];
}

for (int i = 0; i < n; i++) {
    for (int j = 0; j < 3; j++) {
        cin >> m_array[i][j];
    }
}

      //fuction
Multiply(v_array, m_array, o_array, n);
for (int j = 0; j < 3; j++) {
    cout << o_array[j] << " ";
   }
     return 0;
  }

how to fix it to get the correct result? the input is

2 2 -3 2 -3 2 -4

Your issue is here:

for (int k = 0; k < 3; k++)
    o_arr[i] += v_arr[k] * m_arr[k][i];
}

You access elements at indices 0 , 1 and 2 in v_arr , but it only has 2 elements. That's Undefined Behaviour.

Assuming this is matrix*vector multiplication code, it should look like this (untested):

for (int k = 0; k < 3; k++)
    o_arr[k] += v_arr[i] * m_arr[i][k];
}

Also, your loop based on j is useless. You can remove it:

void Multiply(const int v_arr[], const int m_arr[][3], int signed o_arr[], int size)
{
    for(int k = 0; k < 3; k++) { //initialize output array
        o_arr[k] = 0;
    }
    for (int i = 0; i < size; i++) {
        for (int k = 0; k < 3; k++)
            o_arr[k] += v_arr[i] * m_arr[i][k];
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM