[英]complex number calculator in c using functions and structs
我上一篇文章的延续,我正在尝试使用结构和函数编写一个复数计算器。 我的程序必须具有从用户输入中读取复数的函数,并且必须具有用于添加复数的另一个函数。 这是我得到的函数原型:
Complex read_complex(void)
这是我必须使用的原型,无法更改。 现在我正在尝试将我从上述函数扫描的值传递到我的函数中以添加复数。 这是我的代码:
#include <stdio.h>
#include <math.h>
#include<string.h>
typedef struct Complex_ {
double RealPart;
double ImagPart;
} Complex;
Complex read_complex(void);
Complex add_complex(Complex z1, Complex z2);
Complex mul_complex(Complex z1, Complex z2);
int main(void) {
char ent[50];
Complex user1, user2;
printf("Enter Add for addition, Mult for multiplication, MA for magnitude and angle, or Exit to quit: ");
scanf("%s", ent);
if (ent[0] == 'A') {
read_complex();
add_complex(user1, user2);
}
else if (ent[0] == 'M' && ent[1] == 'u') {
read_complex();
mul_complex(user1, user2);
}
else if (ent[0] == 'M' && ent[1] == 'A') {
read_complex();
}
else {
}
return(0);
}
Complex read_complex(void) {
Complex* user1;
Complex* 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.RealPart = z1.RealPart + z2.RealPart;
z3.ImagPart = z1.ImagPart + z2.ImagPart;
printf("(%lf + %lfi) + (%lf + %lfi) = %lf + %lfi", z1.RealPart, z1.ImagPart, z2.RealPart, z2.ImagPart, z3.RealPart, z3.ImagPart);;
return(z3);
}
Complex mul_complex(Complex z1, Complex z2) {
Complex z3;
z3.RealPart = z1.RealPart * z2.RealPart;
z3.ImagPart = z1.ImagPart * z2.ImagPart;
return(z3);
}
(大部分代码现在都不完整,因为我只是想弄清楚添加部分)。 我目前遇到的问题是,当我运行代码时,我收到一条错误消息,指出 user1 和 user2 变量未初始化,而且我不知道如何初始化结构变量。
您似乎对指针的工作方式有误解。
您编写read_complex
的方式,您似乎认为该函数中的指针user1
和user2
自动引用main
函数中的同名变量。 这不是 C 的工作方式。
您实际拥有的是read_complex
内部的两个未初始化指针,然后您尝试通过->
运算符取消引用。 即使声明这样做,您也不会从此函数返回任何内容。
此函数应该返回Complex
的单个副本,因此您应该在本地创建一个副本,将值读入其中,然后返回它。 然后应将返回值分配给局部变量。 所以这也意味着你需要为你阅读的每个Complex
调用这个函数。
此外,您可能想查看如何乘以复数。
这是我得到的函数原型:
Complex read_complex(void)
这是我必须使用的原型,不能更改。
read_complex()
返回 1 个Complex
类型的对象。 用它来读取 1,而不是 2,复数。
让我们使用该函数来读取并创建另一个调用它来读取 2 个复数的函数。
// Receive the address of 2 objects,
// so this code knows where to save the result.
void read_complex2(Complex *a, Complex *b) {
printf("Enter first complex number: ");
*a = read_complex();
printf("Enter the second complex number: ");
*b = read_complex();
}
read_complex()
read_complex()
变得简单: read 2 double
。 检查结果。
Complex read_complex(void) {
Complex x;
if (scanf("%lf %lf", &x.RealPart, &x.ImagPart) != 2) {
fprintf(stderr, "Invalid input.\n");
exit(EXIT_FAILURE);
}
return x;
}
主要的()
调整如下:
if (ent[0] == 'A') {
//read_complex();
read_complex2(&user1, &user2);// Pass in addresses of objects.
add_complex(user1, user2);
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.