c - 如何迭代这个 sin 方程?

标签 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;
}

最佳答案

我想我明白你真正想做的事情:

你的控制变量既不是 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;
}

关于c - 如何迭代这个 sin 方程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55927873/

相关文章:

CAPL 如何使用 memcpy 用零初始化数组

c - Malloc 和 Realloc 结构数组

c - 为什么所有底层的东西都是用 C 写的?

c - 错误 C2371 : 'functionname' redefinition: different basic types

c - Make 仅在第二次运行时使用 VPATH?

c - 重新定位单链表中的节点会导致无限循环

c++ - 将 OpenMP 支持添加到使用 Visual Studio 2010 从 C 文件编译的 mex 文件

c++ - 使用 shmat 和 shmget 与 forks 相乘矩阵

c - 指针运算

c - 如何用表格制作 "global variable"?