c/c++语言开发共享如何使用结构来表示复数

我需要编写一个程序,它使用结构来定义复数,即z1 = x + yi。 然后添加2个复数。 在继续使用我的代码之前,我需要弄清楚如何正确地使用它们。 到目前为止,我已经尝试了一些东西,这是我提出的最好的东西,它仍然没有编译。

这是我的代码的副本,我只需要修复这部分,然后我就可以自己做其余的事了。

#include typedef struct complex1{ float *real1; float *imaginary1; } complex1; typedef struct complex2{ float *real2; float *imaginary2; } complex2; int main(){ struct complex1 real; struct complex1 *realptr; struct complex1 imaginary; struct complex1 *imaginaryptr; struct complex2 real; struct complex2 *realptr; struct complex2 imaginary; struct complex2 *imaginaryptr; printf("Please enter variable x1."); scanf("%d", &real.real1); printf("Please enter variable y1."); scanf("%d", &imaginary.imaginary1); printf("Please enter variable x2."); scanf("%d", &real.real2); printf("Please enter variable y2."); scanf("%d", &imaginary.imaginary2); printf("You have entered: %d,%d,%d,%dn", real.real1, imaginary.imaginary1,real.real2, imaginary.imagnary2); return 0; } 

    文件中有多个错误,但是这样的东西可能更符合您的要求?

     #include typedef struct _complex1{ double real1; double imaginary1; } complex1; 

    不要使用相同的名称两次命名结构,我相信你想跳过real1和imaginary1的指针 – 因为它们没有获得任何东西。

     int main(){ complex1 real; complex1 *realptr; complex1 imaginary; complex1 *imaginaryptr; complex2 real2; complex2 *realptr2; complex2 imaginary2; complex2 *imaginaryptr2; 

    复杂的typedef已告诉编译器它是一个struct。 而且你不能有两个同名的变量。

      printf("Please enter variable x1."); scanf("%lf", &real.real1); 

    您需要将发送到scanf的内容与预期的内容对齐。 %f需要一个double *而不是double **或(在你的情况下为float **)。

    你的代码没什么意义:

    尝试:

     typedef struct { float real; float imaginary; } complex; complex a, b; scanf("%f", &a.real); scanf("%f", &a.imaginary); 

    我会给你一个提示,因为这似乎是一个功课问题。 结构用于将标准数据类型定义或分组在一起以形成新的数据类型,如虚数。 一旦定义,您可以自由使用它。 看起来你正在使用C所以我会继续使用它。 首先定义新类型:

     struct complex { float real; float imaginary; }; 

    在C中,要声明一个struct类型,你通常必须再次输入“struct”,所以大多数程序员也会键入def。 我们可以像这样单独做:

     typedef complex ComplexType; 

    或组合:

     typedef struct complex { float real; float imaginary; } ComplexType; 

    然后申报并分配:

     ComplexType myComplexType; myComplexType.real = 0.5f; myComplexType.imaginary = 0.5f; 

    要么:

     ComplexType myComplexType = { 0.0f, 0.0f }; 

    从那里你可以自由使用你的新类型。 代码中的一些错误是,当您看起来只需要一个时,就会声明两种新的数据类型。 另一种是你正在声明浮点数的指针,这可能不是你需要的。 当你想为堆中的类型分配内存时,通常使用指针。

      以上就是c/c++开发分享如何使用结构来表示复数相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/c-cdevelopment/519196.html

      (0)
      上一篇 2020年12月5日
      下一篇 2020年12月5日

      精彩推荐