如何迭代这个正弦方程?

时间:2019-04-30 19:55:10

标签: c

我无法创建正确的文件。程序中的方程式不会迭代,它只会在请求的任意数量的样本中写入相同的和。

for循环。

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#define LEN 256

int main ()
{
   FILE * fp;
   double i=0; //sample count
   double y=0; //y values
   double f=0; //frequency
   double t=0; //time

   /* open the file for writing*/
   fp = fopen ("1.dat","w");
//fprintf(fp, "sample #\ty-value\n"); 

printf("Enter the frequency in hertz: ");
scanf("%lg", &f);
printf("Enter the number of samples : ");
scanf("%lg", &t);



   /* write 1 seconds of time data into the file stream*/
   for(i = 0; i < t;i++){

//y=sin(i*M_PI/180);
y=sin(2*M_PI*f*t);

//       fprintf (fp, "%g  %g\n",i ,y);
       fprintf (fp, "%g\n",y);
   }

   /* close the file*/  
   fclose (fp);
   return 0;
}

1 个答案:

答案 0 :(得分:0)

我想我知道您真正想做的事

您的控制变量既不是i也不是t,而是i / t,它是每秒t个样本的第i个样本:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#define LEN 256

int main ()
{
    FILE * fp;
    unsigned int i=0; //sample count
    double y=0; //y values
    double f=0; //frequency
    unsigned int t=0; //time

    /* open the file for writing*/
    fp = fopen ("1.dat","w");

    printf("Enter the frequency in hertz: ");
    scanf("%lg", &f);
    printf("Enter the number of samples : ");
    scanf("%u", &t);
    /* write 1 seconds of time data into the file stream*/
    for(i = 0; i < t;i++){
        y=sin(2*M_PI*f*i/t);
        fprintf (fp, "%g\n",y);
    }

    /* close the file*/  
    fclose (fp);
    return 0;
}