c言語初心者です

フォーラム(掲示板)ルール
フォーラム(掲示板)ルールはこちら  ※コードを貼り付ける場合は [code][/code] で囲って下さい。詳しくはこちら
すいか

c言語初心者です

#1

投稿記事 by すいか » 10年前

e^(-t)*sin(t)を計算してグラフ化したいのですが上手くいきません。

コード:

#include "stdafx.h"
#include "math.h"
#include "stdio.h" 
#define N 360 

int _tmain(int argc, _TCHAR* argv[])

    int main(void){ 
	FILE *gp; 
	int i, t; 
	double t, x[N+1], y[N+1]; 

	for(i=0; i<=N; i++){ 
	t = (double)i; 
	x[i]=t; 
	y[i]=exp(-t)*sin(t); 
	} 

	gp = fopen("gnuplot -persist","w"); 
	fprintf(gp, "plot '-' with lines linetype 1\n"); 
	for(i=0; i<=N; i++){ 
	fprintf(gp,"%f\t%f\n", x[i], y[i]); 
	} 
	fprintf(gp,"e\n"); 
	fclose(gp); 


	return 0;
}

アバター
みけCAT
記事: 6734
登録日時: 15年前
住所: 千葉県
連絡を取る:

Re: c言語初心者です

#2

投稿記事 by みけCAT » 10年前

とりあえず、
  • #include "stdafx.h"を削除
  • int _tmain(int argc, _TCHAR* argv[])を削除
  • fopenをpopenに置換
  • fcloseをpcloseに置換
  • Linux (POSIX互換環境)で実行する
fopen(popen)の第一引数に渡しているのと同じコマンドをシェルで打ってgnuplotを起動できるならば、
これでgnuplotの起動はできると思います。
※テストしていないので間違っているかもしれないですし、出力が意図したものになるかはわかりません。

【追記】
  • double型変数tと被ってコンパイルエラーになるので、int型変数tの宣言を削除することが必要です。
  • テストの結果popenはWindowsでも使えました。Linuxで実行する必要は無いようです。
最後に編集したユーザー みけCAT on 2015年6月12日(金) 00:07 [ 編集 1 回目 ]
複雑な問題?マシンの性能を上げてOpenMPで殴ればいい!(死亡フラグ)

アバター
みけCAT
記事: 6734
登録日時: 15年前
住所: 千葉県
連絡を取る:

Re: c言語初心者です

#3

投稿記事 by みけCAT » 10年前

テストを行い、
  • int型変数tの宣言を削除
  • インデントを修正
  • 描画コマンドを標準入力ではなくコマンドラインで与える
  • popenが成功したかをチェックする
  • 必要に応じてterminalを設定させる
という修正を追加しました。

動作確認環境1
Debian リリース 7.8 (wheezy) 64-bit
カーネル Linux 3.2.0-4amd64
GNOME 3.4.2
gcc (Debian 4.7.2-5) 4.7.2
gnuplot 4.6 patchlevel 0
コンパイルオプション: -DUSE_DUMB -lm

動作確認環境2
Windows 7 Home Premium SP1 64ビット
gcc (GCC) 4.8.1
gnuplot 5.0 patchlevel 0
コンパイルオプション : なし

コード:

#include "math.h"
#include "stdio.h"
#define N 360

int main(void){ 
	FILE *gp;
	int i;
	double t, x[N+1], y[N+1];

	for(i=0; i<=N; i++){
		t = (double)i;
		x[i]=t;
		y[i]=exp(-t)*sin(t);
	} 

#ifdef USE_DUMB
	gp = popen("gnuplot --persist -e \"set terminal dumb; plot '-' with lines linetype 1\"","w");
#else
	gp = popen("gnuplot --persist -e \"plot '-' with lines linetype 1\"","w");
#endif
	if (gp == NULL) {
		perror("popen");
		return 1;
	}

	for(i=0; i<=N; i++){
		fprintf(gp,"%f\t%f\n", x[i], y[i]);
	}
	pclose(gp);

	return 0;
}
複雑な問題?マシンの性能を上げてOpenMPで殴ればいい!(死亡フラグ)

アバター
みけCAT
記事: 6734
登録日時: 15年前
住所: 千葉県
連絡を取る:

Re: c言語初心者です

#4

投稿記事 by みけCAT » 10年前

標準入力からデータを書き込んでもできるようですね。(前述のWindows環境で確認)

コード:

#include "math.h"
#include "stdio.h"
#define N 360


int main(void){
	FILE *gp;
	int i;
	double t, x[N+1], y[N+1];

	for(i=0; i<=N; i++){
		t = (double)i;
		x[i]=t;
		y[i]=exp(-t)*sin(t); 
	}

	gp = popen("gnuplot -persist","w");
	fprintf(gp, "plot '-' with lines linetype 1\n");
	for(i=0; i<=N; i++){
		fprintf(gp,"%f\t%f\n", x[i], y[i]);
	}
	fprintf(gp,"e\n");
	pclose(gp);

	return 0;
}
複雑な問題?マシンの性能を上げてOpenMPで殴ればいい!(死亡フラグ)

すいか

#5

投稿記事 by すいか » 10年前

回答ありがとうございました

閉鎖

“C言語何でも質問掲示板” へ戻る