如何从键盘读取复数?我的意思是我不能使用scanf或get(在C中)

时间:2014-03-24 05:11:36

标签: c

我将z3声明为复数,我希望用户输入,但我不知道如何阅读实部和虚部并将其保存在z3中。我想我既不能使用scanf也不能使用。这是代码。

void main(void)
{
    float complex z1= 1.0 + 3.0 * I;
    float complex z2= 1.0 - 4.0 * I;
    float complex z3;

    float complex sum= z1 + z2;

    printf("\nLa suma Z1+Z2 = %.2f %+.2fi\n",crealf(sum),cimagf(sum));

    printf("\nIngrese la parte real de Z3... ");
    ///??????? 
    printf("\nIngrese la parte imaginaria de Z3... ");
    ///???????
    //How can I read and saved a complex number?
}

1 个答案:

答案 0 :(得分:0)

您可以像这样使用scanf:

typedef struct complex_num
{
    float f_real;
    float f_img;
}complex_num_t;

complex_num_t get_complex_num()

{
    complex_num_t complex_num= {0,0};
    printf("Enter real part:");
    scanf("%f",&complex_num.f_real);
    printf("Enter imaginery part:");
    scanf("%f",&complex_num.f_img);
    return complex_num;
}

void main(void)
{
float complex z1= 1.0 + 3.0 * I;
float complex z2= 1.0 - 4.0 * I;
float complex z3;

complex_num_t input_num = {0,0};

float complex sum= z1 + z2;

printf("\nLa suma Z1+Z2 = %.2f %+.2fi\n",crealf(sum),cimagf(sum));

/*Metod 1: Ask real and imaginary independently*/
input_num = get_complex_num();
z3 = input_num.f_real + input_num.f_img*I;

printf("\nIngrese la parte real de Z3...%f ",crealf(z3));
printf("\nIngrese la parte imaginaria de Z3...%f ",cimagf(z3));

}