0
두 개의 복소수 배열을 추가하기 위해 C로 프로그램을 작성하려고합니다.구조체에 대한 포인터와 구조체에 대한 포인터가있는 무작위 결과
#include <stdlib.h>
#include <stdio.h>
typedef struct cplx
{
int re;
int im;
} cplx;
cplx* sum(cplx *x, cplx *y,int n)
{
int i;
cplx *z = malloc(n * sizeof(cplx));
if (z == NULL) {return NULL;}
for(i=0;i<n;i++)
{
z[i].re=x[i].re+y[i].re;
z[i].im=x[i].im+y[i].im;
}
return z;
}
cplx* difference(cplx *x, cplx *y, int n)
{
int i;
cplx *z = malloc(n * sizeof(cplx));
if (z == NULL) {return NULL;}
for(i=0;i<n;i++)
{
z[i].re=x[i].re-y[i].re;
z[i].im=x[i].im-y[i].im;
}
return z;
}
cplx* sumdiff(cplx *x,cplx *y, int n,cplx* (*op)())
{
return(op(x,y,n));
}
int main(void)
{
cplx *z1,*z2,*s,*diff;
int m,n,i;
printf("Give the number of complex numbers to add and subtract:");
scanf("%d",&n);
z1=malloc(n*sizeof(cplx));
z2=malloc(n*sizeof(cplx));
s=malloc(n*sizeof(cplx));
diff=malloc(n*sizeof(cplx));
if (z1==NULL || z2==NULL || s==NULL || diff==NULL)
{
printf("Allocation failed.\nEnding program.");
exit(0);
}
printf("Give the numbers of the first vector:\n");
for(i=0;i<n;i++)
{
printf("Re(z1[%d])=",i+1); scanf("%d",&m);
z1[i].re=m;
printf("Im(z1[%d])=",i+1); scanf("%d",&(z1[i].im));
}
printf("Give the numbers of the second vector:\n");
for(i=0;i<n;i++)
{
printf("Re(z2[%d])=",i+1); scanf("%d",&(z2[i].re));
printf("Im(z2[%d])=",i+1); scanf("%d",&(z2[i].im));
}
s=sum(z1,z2,n);
diff=difference(z1,z2,n);
s=sumdiff(z1,z2,n,sum);
diff=sumdiff(z1,z2,n,difference);
for(i=0;i<n;i++)
{
printf("z1[%d]+z2[%d]=%d+j(%d)\nz1[%d]+z2[%d]=%d+j(%d)\n",i+1,i+1,s[i+1].re,s[i+1].im,i,i,diff[i+1].re,diff[i+1].im);
}
free(z1); free(z2); free(s); free(diff);
return 0;
}
그러나 때 입력 :
Give the number of complex numbers to add and subtract:1
Give the numbers of the first vector:
Re(z1[1])=1
Im(z1[1])=1
Give the numbers of the second vector:
Re(z2[1])=1
Im(z2[1])=1
출력은 다음과 같습니다
z1[1]+z2[1]=760368231+j(134222413)
z1[1]+z2[1]=1884507195+j(4685)
가 난 단지 난수를 얻을
나는 다음과 같은 코드를 사용하고 있습니다.
내가 뭘 잘못하고 있니?
프로그램 부분을 테스트하는 기술을 개발해야합니다. 전체 프로그램을 작성하고 실행하며 발견하는 것이 좋지 않습니다. 개별 기능 및 작업을 분리하고 테스트하여 오류를 수정할 수 있습니다. 그러면 문제를 좁힐 수 있습니다. – paddy
어떻게 그럴 수 있습니까? –
C99에는 [내장 된'_Complex' 유형] (https://en.wikipedia.org/wiki/Complex.h#complex.h)이 있습니다. – michaelb958