Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Complex numbers through scanf in C

Tags:

c

I have problem with following fragment of code:

int main()
{
    int n = 3;

    complex_t t[3];
    for(int i = 0; i < n; i++)
    {
        double x, y;
        printf("Enter complex number: ");
        scanf("%f %f", &x, &y);
        t[i].re = x;
        t[i].im = y;
    }
}

When I am trying to pass x, and y to the program, it doesn't change value, and is 0.00000. Can you help me?

like image 800
Pytacz Avatar asked Apr 10 '26 00:04

Pytacz


1 Answers

You've declared x and y as doubles, but then went on to use the format specifier for floats (%f). So the end result is reading them in as if they were regular floats, then jamming the result into a double leaving you with unexpected values when trying to actually use them.

You need to use the format specifier specifically for doubles (%lf) here.

scanf("%lf %lf", &x, &y);

See format string specifications for more information about different format specifiers.

like image 186
codyne Avatar answered Apr 12 '26 15:04

codyne



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!