Удаление комментариев перед #include ‹math.h› уничтожает мой код

Программа попросит пользователя ввести действительную и мнимую части двух комплексных чисел. Программа должна выводить сумму, разность, произведение, частное и абсолютное значение комплексных чисел, отформатированных до двух знаков после запятой.

Все работало, за исключением части кода со значением абс, всякий раз, когда я его запускаю, я получаю действительно странные числа там, где должно быть значение абс, например -1,644534634 или -1,4363465.

Пока я искал, я заметил, что забыл добавить #include <math.h> вверху, однако, когда я это делаю, все портится, и я получаю 61 ошибку о том, что .real и .img не являются частью комплекса.

Если возможно, не могли бы вы взглянуть на мой метод значения абс и посмотреть, правильно ли я его написал, спасибо.

#include <stdio.h>
//#include <math.h>

struct complex
{
    float real;
    float img;
};

struct complex add_complex(struct complex c1, struct complex c2);
struct complex subtract_complex(struct complex c1, struct complex c2);
struct complex multiply_complex(struct complex c1, struct complex c2);
struct complex divide_complex(struct complex c1, struct complex c2);
double abs_complex(struct complex c);

void main()
{
    struct complex c, c1, c2, tempa, temps, tempm, tempd;
    double abs1, abs2;

    printf("Enter the real part of the 1st complex number:\n");
    scanf("%f", &c1.real);
    printf("Enter the imaginary part of the 1st complex number:\n");
    scanf("%f", &c1.img);
    printf("Enter the real part of the 2nd complex number:\n");
    scanf("%f", &c2.real);
    printf("Enter the imaginary part of the 2nd complex number:\n");
    scanf("%f", &c2.img);

    tempa = add_complex(c1, c2);
    temps = subtract_complex(c1, c2);
    tempm = multiply_complex(c1, c2);
    tempd = divide_complex(c1, c2);
    abs1 = abs_complex(c1);
    abs2 = abs_complex(c2);

    printf("\n");

    if (tempa.real == 0)
        printf("(%.2f + %.2fi) + (%.2f + %.2fi) = (%.2fi)\n", c1.real, c1.img, c2.real, c2.img, tempa.img);
    else if (tempa.img == 0)
        printf("(%.2f + %.2fi) + (%.2f + %.2fi) = (%.2f)\n", c1.real, c1.img, c2.real, c2.img, tempa.real);
    else
        printf("(%.2f + %.2fi) + (%.2f + %.2fi) = (%.2f + %.2fi)\n", c1.real, c1.img, c2.real, c2.img, tempa.real, tempa.img);

    if (temps.real == 0)
        printf("(%.2f + %.2fi) - (%.2f + %.2fi) = (%.2fi)\n", c1.real, c1.img, c2.real, c2.img, temps.img);
    else if (temps.img == 0)
        printf("(%.2f + %.2fi) - (%.2f + %.2fi) = (%.2f)\n", c1.real, c1.img, c2.real, c2.img, temps.real);
    else
        printf("(%.2f + %.2fi) - (%.2f + %.2fi) = (%.2f + %.2fi)\n", c1.real, c1.img, c2.real, c2.img, temps.real, temps.img);

    if (tempm.real == 0)
        printf("(%.2f + %.2fi) * (%.2f + %.2fi) = (%.2fi)\n", c1.real, c1.img, c2.real, c2.img, tempm.img);
    else if (tempm.img == 0)
        printf("(%.2f + %.2fi) * (%.2f + %.2fi) = (%.2f)\n", c1.real, c1.img, c2.real, c2.img, tempm.real);
    else
        printf("(%.2f + %.2fi) * (%.2f + %.2fi) = (%.2f + %.2fi)\n", c1.real, c1.img, c2.real, c2.img, tempm.real, tempm.img);

    if (tempd.real == 0)
        printf("(%.2f + %.2fi) / (%.2f + %.2fi) = (%.2fi)\n", c1.real, c1.img, c2.real, c2.img, tempd.img);
    else if (tempd.img == 0)
        printf("(%.2f + %.2fi) / (%.2f + %.2fi) = (%.2f)\n", c1.real, c1.img, c2.real, c2.img, tempd.real);
    else
        printf("(%.2f + %.2fi) / (%.2f + %.2fi) = (%.2f + %.2fi)\n", c1.real, c1.img, c2.real, c2.img, tempd.real, tempd.img);

    printf("|(%.2f + %.2fi)| = (%.2d)\n", c1.real, c1.img, abs1);
    printf("|(%.2f + %.2fi)| = (%.2d)\n", c2.real, c2.img, abs2);

    printf("\n");
}

struct complex add_complex(struct complex c1, struct complex c2)
{
    struct complex tempa;
    tempa.real = c1.real + c2.real;
    tempa.img = c1.img + c2.img;
    return(tempa);
}

struct complex subtract_complex(struct complex c1, struct complex c2)
{
    struct complex temps;
    temps.real = c1.real - c2.real;
    temps.img = c1.img - c2.img;
    return(temps);
}

struct complex multiply_complex(struct complex c1, struct complex c2)
{
    struct complex tempm;
    tempm.real = c1.real*c2.real - c1.img*c2.img;
    tempm.img = c1.real*c2.img + c1.img*c2.real;
    return(tempm);
}

struct complex divide_complex(struct complex c1, struct complex c2)
{
    struct complex tempd, temp1, temp2;
    temp1.real = c1.real*c2.real + c1.img*c2.img;
    temp2.real = c2.real*c2.real + c2.img*c2.img;
    temp1.img = c1.img*c2.real - c1.real*c2.img;
    temp2.img = c2.real*c2.real + c2.img*c2.img;
    tempd.real = temp1.real / temp2.real;
    tempd.img = temp1.img / temp2.img;
    return(tempd);
}

double abs_complex(struct complex c)
{
    double temp1, temp2;
    double abs;
    temp1 = c.real*c.real;
    temp2 = c.img*c.img;
    abs = sqrt(temp1 + temp2);
    return(abs);

}

person Sean    schedule 30.09.2014    source источник


Ответы (1)


Часть 1:

Вполне возможно, что math.h включает complex.h, что создаст этот макрос:

#define complex _Complex

Я предлагаю переименовать ваш сложный тип или использовать встроенный, описанный здесь.

Вы также можете обойтись без выполнения #undef complex после #include <main.h>, но для больших программ это, вероятно, нецелесообразно.

Часть 2:

Вы используете неправильный спецификатор формата при печати абсолютных значений. Вот предупреждения от clang, которые ясно объясняют проблему и предлагают решение:

foo.c:68:60: warning: format specifies type 'int' but the argument has type 'double' [-Wformat]
    printf("|(%.2f + %.2fi)| = (%.2d)\n", c1.real, c1.img, abs1);
                                ~~~~                       ^~~~
                                %.2f
foo.c:69:60: warning: format specifies type 'int' but the argument has type 'double' [-Wformat]
    printf("|(%.2f + %.2fi)| = (%.2d)\n", c2.real, c2.img, abs2);
                                ~~~~                       ^~~~
                                %.2f
person Bill Lynch    schedule 30.09.2014
comment
Это решило мою проблему с ошибкой 61! Большое спасибо. Не могли бы вы теперь помочь мне с функцией значения абс? Я все еще получаю действительно большие ответы. Похоже, что функция sqrt не выполняет свою работу. - person Sean; 30.09.2014
comment
Проблема с math.h определением complex кажется проблемой Microsoft C. Заголовок math.h не должен этого делать (в math.h MSVC есть комментарий, в котором говорится: имя, отличное от ANSI, для совместимости, где оно определяет). - person Michael Burr; 30.09.2014
comment
О, я забыл, что %d — это еще один способ включить int, а не double. Спасибо вам за это! - person Sean; 30.09.2014