【问题标题】:complex number calculator: arithmetic operations with struct variables in c复数计算器:c 中结构变量的算术运算
【发布时间】:2021-12-13 23:20:23
【问题描述】:

尝试编写一个可以进行复数计算的 c 程序。程序必须使用这种结构:

typedef struct Complex_ {
    double RealPart;
    double ImagPart;
} Complex;

它必须使用一个函数来读取用户输入的复数,另一个函数来添加它们,另一个函数来相乘,等等。我现在正试图让这个函数来添加数字,我'正在试图弄清楚如何做到这一点。这是用于读取用户输入的函数:

Complex read_complex(void) {
    Complex user1, user2;
    printf("Enter first complex number: ");
    scanf("%lf %lf", &user1.RealPart, &user1.ImagPart);
    printf("Enter the second complex number: ");
    scanf("%lf %lf", &user2.RealPart, &user2.ImagPart);

return;

}

这就是我到目前为止添加复数的方法:

Complex add_complex(Complex z1, Complex z2) {
    Complex z3;

    z3 = z1 + z2;//error on this line

    return(z3);

}

函数必须返回 z3,z3 必须等于 z1 + z2,z1 和 z2 必须是 Complex 类型的变量。我不知道如何使它符合这些规范,因为你不能对结构变量进行算术运算。

【问题讨论】:

  • 您将不得不在某处编写自己的代码,以显式地将实部添加到实部,将复杂部分添加到复杂部分。如您所见,您不能将+ 运算符应用于两个结构并期望它们被神奇地添加; C 没有办法解决这个问题。 (您可以让它在具有运算符重载的C++中工作。)
  • 请注意,从 C99 开始,该语言本身就支持复数。只需包含complex.h
  • 我希望您的read_complex 功能比显示的更多。 user1user2 是该函数的本地函数,您只能 return 其中一个(并且您目前没有返回任何内容)。如果您希望用户输入的内容保留在该函数之外,则需要将它们作为指针传递。

标签: c function struct


【解决方案1】:

不是您要问的,但您的 read_complex 函数如图所示将不起作用。建议改成如下内容

#include <stdbool.h>

bool read_complex(Complex* user1, Complex* user2)
{
  bool inputValid = false;
  
  // weak check for validity, a non-NULL pointer isn't necessarily
  // valid. In fact, probably better to skip this check and instead
  // document/accept UB if user1 and/or user2 are not valid pointers.
  if (user1 != NULL && user2 != NULL)
  {
    printf("Enter first complex number: ");
    if (scanf("%lf %lf", &(user1->RealPart), &(user1->ImagPart)) == 2)
    {
      printf("Enter the second complex number: ");
      if (scanf("%lf %lf", &(user2->RealPart), &(user2->ImagPart)) == 2)
      {
        inputValid = true;
      } // else, print error message?
    } // else, print error message?
  }

  return inputValid;
}

scanf 返回一个int,指示与提供的格式说明符匹配的输入数量。每个输入应该是 2,如果不是,你知道有问题。 read_complex 的调用者可以决定如果它返回false 下一步要做什么。

【讨论】:

    【解决方案2】:

    您不能添加或减去数据结构。

    Complex add_complex(Complex z1, Complex z2) {
        Complex z3;
    
        z3.RealPart = z1.RealPart + z2.RealPart;
        z3.ImagPart = z1.ImagPart + z2.ImagPart;
    
        return(z3);
    }
    

    【讨论】:

      猜你喜欢
      • 2013-06-27
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-18
      • 1970-01-01
      相关资源
      最近更新 更多