问题:正在打印负值
#include<stdio.h>
//structure defination
struct complex
{
float r;
float i;
};
typedef struct complex CMPLX;
// addition is done here
CMPLX add(CMPLX a,CMPLX b)
{
CMPLX c; //structure of c
c.r = a.r+b.r;
c.i=a.i+b.i;
return c;
}
//function to read
CMPLX read(CMPLX r)
{
printf("enter real part of complex number ");
scanf("%f",&r.r);
printf("\n");
printf("enter imaganary part of complex number ");
scanf("%f",&r.i);
printf("\n");
return r;
}
//function to write
void write(CMPLX w)
{
printf("real part= %f and imaginary part is %f",w.r,w.i);
printf("\n");
}
void main()
{
CMPLX a;
CMPLX b;
CMPLX c;
printf("\n");
printf("enter first complex number");
printf("\n");
read(a);
printf("complex numbes is");
printf("\n");
write(a);
printf("\n");
printf("enter second complex number");
printf("\n");
read(b);
printf("complex numbes is");
write(b);
printf("\n");
c=add(a,b);
printf("added complex number");
printf("\n");
write(c);
}
答案 0 :(得分:2)
read(a);
应为a = read();
。
您不使用返回的值(参数在C中按值传递),因此您在read()
中输入的值不会分配给main
的{{1}}。您看到的值将基于存储a
的内存中的垃圾。
此外,a
的参数无效,因为您只需将其视为局部变量。而只是在read
内声明一个局部变量r
,然后返回。
如果你在POSIX系统上,那么将你的函数称为read
和read
以外的函数会很好,因为它们可能与这些名称的POSIX函数冲突。
另一个好主意是检查write
是成功还是失败(在你的案例中成功返回scanf
)。如果您不这样做,那么输入字母将导致您的程序出现故障。
答案 1 :(得分:0)
添加后,该值超出了浮动限制。尝试使用double而不是float。
答案 2 :(得分:0)
您的read()
函数返回一个值,但忽略它返回的值。您还通过未初始化的值传递参数。您需要删除参数,并使用返回值:
CMPLX read(void) { CMPLX r; …other code as before… }
a = read();
等
您在代码中也存在拼写错误和不一致的问题。一致性在编程中非常重要;如果拼写得很好也很好,但是一致性更重要。
每次使用时都应检查scanf()
是否有效。
此外,除非您在Windows上进行编程,否则使用void main()
是不合法的。 main()
的返回类型为int
,除非您的实现允许您使用其他类型。