Parseval
Parseval

Reputation: 843

Function does not update value of variable

I'm trying to write a program that multiplies two different complex numbers (b*c), stores the result in a prints out the result. For the purposes of keeping it simple here I've only decided to use 10 numbers and set all the imaginary and real values for b and c to the numbers 0 through 9.

First I create arrays that will contain the real and imaginary parts of the complex numbers a, b and c. Next I declare the real and imaginary part of a to be zero since I don't know these yet. To find these, I have a function named multiply that computes the real and imaginary parts of a.

Finally, in my main method I loop through all the arrays, generate values 0-9, use multiply to populate the arrays of a (as_re and as_im) containing the real and imaginary values of a, then simply printing all of these entries out.

However I only get: The product is 0 + 0i on every iteration. This has to mean that my multiply function does not update the values of a_re and a_im. Can anyone help me understand why?

My code is below:

#include <stdio.h>
#include <stdlib.h>

void multiply(int c_re, int c_im, int a_re, int a_im, int b_re, int b_im);

int as_re[10];
int as_im[10];
int bs_re[10];
int bs_im[10];
int cs_re[10];
int cs_im[10];

int a_re = 0;
int a_im = 0;

int main(){

   for (int i = 0; i < 10; i++){

      bs_re[i] = i;
      bs_im[i] = i;
      cs_re[i] = i;
      cs_re[i] = i;

      multiply(cs_re[i], cs_im[i], as_re[i], as_im[i], bs_re[i], bs_im[i]);

      as_re[i] = a_re;
      as_im[i] = a_im;

      printf("The product is %d + %di\n", as_re[i], as_im[i]);
   }

}

void multiply(int c_re, int c_im, int a_re, int a_im, int b_re, int b_im){

   a_re = c_re * b_re - c_im * b_im;
   a_im = c_re * b_im + c_im * b_re;

}

Upvotes: 0

Views: 55

Answers (1)

Sai
Sai

Reputation: 1700

You don't need to pass global variables as parameters. If you declare a parameter or local variable with the same name as the global variable then it will hide the global variable in that function.

Removed the global variables which were included as parameters for your function.

#include <stdio.h>
#include <stdlib.h>

void multiply(int c_re, int c_im, int b_re, int b_im);

int as_re[10];
int as_im[10];
int bs_re[10];
int bs_im[10];
int cs_re[10];
int cs_im[10];

int a_re = 0;
int a_im = 0;

int main(){

   for (int i = 0; i < 10; i++){

      bs_re[i] = i;
      bs_im[i] = i;
      cs_re[i] = i;
      cs_re[i] = i;

      multiply(cs_re[i], cs_im[i], bs_re[i], bs_im[i]);

      as_re[i] = a_re;
      as_im[i] = a_im;

      printf("The product is %d + %di\n", as_re[i], as_im[i]);
   }

}

void multiply(int c_re, int c_im, int b_re, int b_im){

   a_re = c_re * b_re - c_im * b_im;
   a_im = c_re * b_im + c_im * b_re;

}

Upvotes: 1

Related Questions