構造体

  • 構造体を使ってみる
    • 値列の要素数・平均・標本分散・不偏分散を持つ構造体を作ってみる
    • ヘッダファイルで構造体の作りを宣言("DescriptionStat.h"というファイル)
// DescriptionStat.h
struct DescStat {
	int n;	//number of values
	double m;	//mean
	double sv;	//sample variance
	double uv;	//unbiased variance
};
    • DescStat構造体を使うstrprac.c。, "MT.h"と"DescriptionStat.h"をインクルードする
//strprac.c
# include <stdio.h>
# include "DescriptionStat.h"
#include <time.h>
#include <math.h>
#include "MT.h"

main () {
	int i,j;
	int niter = 3;
	int nr = 100;
	struct DescStat A[niter]; 
	for(i = 0; i < niter; i++){
		double rtmp[nr];
		for(j = 0; j < nr; j++){
			rtmp[j] = genrand_real3();
		}
		double tmpm = 0;
		for(j = 0; j < nr; j++){
			tmpm += rtmp[j];
		}
		tmpm /= nr;
		double tmpsv = 0;
		for(j = 0; j < nr; j++){
			tmpsv += pow((rtmp[j]-tmpm),2);
		}
		tmpsv /= nr;
		struct DescStat tmpA = {nr,tmpm,tmpsv,tmpsv*nr/(nr-1)};
		A[i] = tmpA;
	}
	printf("N.elements\tMean\tsample.variance\tunbiased.variance\n");
	for(i = 0; i < niter; i++) {
		printf("%d\t%f\t%f\t%f\n",A[i].n, A[i].m,A[i].sv,A[i].uv);
	}
	return 0;
}
    • 実行結果
ryamada@CFS10 ~
$ gcc -o strprac strprac.c

ryamada@CFS10 ~
$ ./strprac.exe
N.elements      Mean    sample.variance unbiased.variance
100     0.543772        0.097448        0.098432
100     0.523272        0.078582        0.079376
100     0.486063        0.085874        0.086742

ryamada@CFS10 ~
  • 構造体は代入できる
//strprac.c
# include <stdio.h>
# include "DescriptionStat.h"
#include <time.h>
#include <math.h>
#include "MT.h"

main () {
	int i,j;
	int niter = 3;
	int nr = 100;
	struct DescStat A[niter]; 
	for(i = 0; i < niter; i++){
		double rtmp[nr];
		for(j = 0; j < nr; j++){
			rtmp[j] = genrand_real3();
		}
		double tmpm = 0;
		for(j = 0; j < nr; j++){
			tmpm += rtmp[j];
		}
		tmpm /= nr;
		double tmpsv = 0;
		for(j = 0; j < nr; j++){
			tmpsv += pow((rtmp[j]-tmpm),2);
		}
		tmpsv /= nr;
		struct DescStat tmpA = {nr,tmpm,tmpsv,tmpsv*nr/(nr-1)};
		A[i] = tmpA;
	}
	A[2] = A[1]; // 構造体同士の代入は可能である。(構造体変数 = 構造体変数 のように書いて良いということ)
	printf("N.elements\tMean\tsample.variance\tunbiased.variance\n");
	for(i = 0; i < niter; i++) {
		printf("%d\t%f\t%f\t%f\n",A[i].n, A[i].m,A[i].sv,A[i].uv);
	}
	return 0;
}
ryamada@CFS10 ~
$ gcc -o strprac strprac.c

ryamada@CFS10 ~
$ ./strprac.exe
N.elements      Mean    sample.variance unbiased.variance
100     0.543772        0.097448        0.098432
100     0.523272        0.078582        0.079376
100     0.523272        0.078582        0.079376

ryamada@CFS10 ~