f(t)= {t + 3:t∈[0,T]。
0:否则}
读取T的整数值。在t = 0,1,2处采样上面的函数f(t)。 。 。 T,然后将值写入文件“ function.txt”。
从文件中读取值,并将它们放置在数组中。
编写一个称为“卷积”的函数,该函数将两个数组作为参数,计算它们的离散卷积并在两列中输出结果函数:索引和卷积。将输出打印到屏幕和名为“ convolution.txt”的文件中。您的函数应该只对与卷积的非零值相对应的索引进行计算。假设两个函数在0和T之间仅是非零的(提示:卷积在0和2T之间仅是非零的-请确保您了解原因。)
使用第1部分中相同数组给出的函数f和g调用函数。 查找卷积的公式是
(f * g)[n] ∑(f [m] g [n-m])
这是我到目前为止所拥有的。需要帮助完成它。
#include <stdlib.h>
#include <stdio.h>
void convolution (int F[ ] ,int G [ ])
{
FILE *fptr;
int i,j,T;
int x;
F[T],G[T];
x= T+1;
fptr = fopen("function.txt","r");
if (fptr == NULL)
{
printf("No such file!");
exit(0);
}
for (i=0; i<=x; i++)
{
F[i]= i+3;
fscanf(fptr,"%d",&j);
printf("F[%d] = %d\n",i,F[i]);
}
printf("\n");
fclose(fptr);
int sum;
for (c=0; c<2T+1; c++)
{
sum =0; g=c;
for(f=0; f<c; f++,g--)
{
if (f<=T && g<=T)
{
sum = sum + F [ ]* G [ ];
}
printf("convolution [%d] = %d",c, sum);
}
}
}
int main (void)
{
int x;
int T,F[x],G[x];
x= T+1;
printf("Enter the value of T: ");
scanf("%d",&T);
convolution(F,G);
return 0;
}
答案 0 :(得分:0)
您的代码中有许多未初始化的变量。在将它们写入之前读取它们会导致未定义的行为。
例如,在main
中,变量x
未初始化。您正在使用它来定义可变长度数组F[x]
和G[x]
。
在convolution
函数中,有效的T
未初始化。并且您在语句x= T+1;
中使用它的值
这是未定义的行为。请查看此question及其答案。
即使T
的初始值发生为0,由于for
的值也无法到达内部c
循环超过1。
答案 1 :(得分:0)
您的普通声明中有些混乱:
int main (void)
{
int x;
int T,F[x],G[x]; <==== x is not initialized. You define arrays of random length. Might be 0.
x= T+1; <==== T is not initialized.
printf("Enter the value of T: ");
scanf("%d",&T); <==== now T has a value but it is never used.
convolution(F,G);
return 0;
}
然后在被调用的函数中重复同样的问题:
void convolution (int F[ ] ,int G [ ])
{
FILE *fptr;
int i,j,T;
int x;
F[T],G[T]; <=== T is not initialized; You access random elements of arrays of unknown random length.
x= T+1; <=== T is still not initialized.
然后灾难加速...;)
for (i=0; i<=x; i++) <== x is T+1 (still uninitialized)
{
F[i]= i+3; <== With i going up to x which is T+1 you access index T+1 of an array of size [T] which is out of bounds.
fscanf(fptr,"%d",&j);
printf("F[%d] = %d\n",i,F[i]);
}
您应该从变量开始。