0

I write a code about the complex number's subtraction,addition,multiplication and division.

input:
1+2i 2+2i +
output:
3+4i
I use visual studio 2013.
It show the wrong message about I : expression must have arithmetic type.
In line:z1 = real+imag*I; z2 = real+imag*I;
What should I do to solve this?

This is my code :

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

#define N 100
double ToNum(char *c);


int main(){

_Dcomplex z1, z2, z3;
char c1[N], c2[N];
char *p = c1;
char op;
double imag, real,op1, op2;

scanf("%s%s%c", c1, c2, &op);

    real = ToNum(c1);
    while (*p != '+' && *p != '-')
        p++;
    op1= *p == '+' ? 1 : -1;
    imag = ToNum(++p);
    imag *= op1;
    z1 = real+imag*I;

    real = ToNum(c2);
    while (*p != '+' && *p != '-')
        p++;
    op2 = *p == '+' ? 1 : -1;
    imag = ToNum(++p);
    imag *= op2;
    z2 = real + imag*I;


    if (op == '+')
    z3 = z1 + z2;
    else if (op == '-')
    z3 = z1 - z2;
    else if (op = '*')
    z3 = z1*z2;
    else if (op == '/')
    z3 = z1 / z2;

    printf("%lf%+lfi\n", creal(z3), cimag(z3));

return 0;
}

double ToNum(char *c)
{
double num = 0; 
num = atof(c);
return num;
}
NaiveRed
  • 65
  • 1
  • 9
  • `complex` is a C99 feature, I don't believe VC supports it. (http://msdn.microsoft.com/en-us/library/a86zba5c.aspx doesn't list `_Compex` as a type specifier.) – Mat Dec 21 '14 at 09:33
  • 1
    I'm pretty sure Visual Studio's support for complex numbers is [very much incomplete](http://stackoverflow.com/questions/22991409/compiling-c-code-in-visual-studio-2013-with-complex-h-library). They've only added enough parts of `complex.h` to be compliant with C++11. You'll have to either avoid Microsoft's compiler if you want to use C's complex types or use C++'s complex types instead. – Rufflewind Dec 21 '14 at 09:36
  • Works at https://ideone.com/5wiHB6 when C99 compilation is used the unrecognised `_Dcomplex` is replaced with `double complex` and the `else if (op = '*')` error is corrected. Possibly stdlib.h defined a symbol also named `I`; try reordering the header inclusions. – Clifford Dec 21 '14 at 09:39
  • 2
    He's using Visual Studio which has terrible support for C99. – Rufflewind Dec 21 '14 at 09:40
  • 1
    Its C++ support is good however, and that has much better support for complex numbers. – Clifford Dec 21 '14 at 09:41

0 Answers0