7回目 課題解答・解説
#include <stdio.h> #include <math.h> void clear_array(double x[], int n); // 要素数 n の配列 x に,すべて 0 を代入する(初期化). void square_wave(double x[], int n); // 要素数 n の配列 x に,任意の周波数(例えば 5 )の矩形波を書き込む.振幅は任意,例えば -1 から 1 など. void sin_waves(double x[], int n, double f1, double f2, double f3); // 配列に周波数 f1, f2, f3,計3個の正弦波または余弦波の和を入れる. int main(){ const int n = 100; double x1[n] = {0}, x2[n] = {0}; FILE *fp; //配列の初期化 clear_array(x1, n); clear_array(x2, n); //配列に各波形の値を代入 square_wave(x1, n); sin_waves(x2, n, 2, 10, 100); //ファイル出力 fp = fopen("153R000000-07-1.csv", "w"); if(fp == NULL){ printf("file cannot be opened\n"); return -1; } fprintf(fp, "矩形波,合成波\n"); for(int i = 0; i < n; i++){ fprintf(fp, "%f,%f\n", x1[i], x2[i]); } fclose(fp); return 0; } void clear_array(double x[], int n){ for(int i = 0; i < n; i++){ x[i] = 0; } } void square_wave(double x[], int n){ int freq = 5; //任意の半周波数をここで設定 for(int i = 0; i < n; i++){ if((i/freq)%2 == 0) x[i] = -1; //iを任意の半周期で割った解の整数の位が2の倍数なら-1を代入,それ以外で1を代入 else x[i] = 1; } } void sin_waves(double x[], int n, double f1, double f2, double f3){ for(int i = 0; i < n; i++){ x[i] = (2.0 * sin(2*M_PI*i/n * f1) //M_PIはmath.hに定義される円周率の定数 + 0.5 * cos(2*M_PI*i/n * f2) + 0.25 * sin(2*M_PI*i/n * f3)); } } |