2.データ構造
(1) 年月日から曜日を求める
#include "stdafx.h"
// ツェラー(Zeller)の公式
int WeekDay(int Y, int M, int D)
{ int YY=Y; int MM=M;
if (M<3){YY=Y-1; MM=M+12;}
return (YY +(YY/4)-(YY/100)+(YY/400)+(13*MM + 8)/5+D) % 7;
}
int main(int argc, char* argv[])
{ int Y,M,D;
printf("Year : "); scanf("%d",&Y);
printf("Month: "); scanf("%d",&M);
printf("Day : "); scanf("%d",&D);
int R=WeekDay(Y,M,D);
char X[7][4]={"日","月","火","水","木","金","土"};
printf("\n%04d/%02d/%02dは, %s曜日です。\n\n",Y,M,D,X[R]);
return 0;
}
|
|
|
|
(2) 構造体の例(体重の判定)
#include "stdafx.h"
struct physique_data /*体格データ*/
{ char Name[20]; float Weight,Height;
};
void strcopy(char a[],char b[])
{ int i;
for(i=0;a[i] !=0;i++) b[i]=a[i];
b[i]='\0';
}
int main(int argc, char* argv[])
{ physique_data X;char S[10];
printf("氏名 : "); scanf("%s", &X.Name);
printf("体重 : "); scanf("%f", &X.Weight);
printf("身長 : "); scanf("%f", &X.Height);
double S_Weight=X.Height * X.Height * 22/10000;
double Fat=(X.Weight - S_Weight)/S_Weight;
if(Fat>=0.1) strcopy("太りすぎ",S);
else if(Fat<=-0.1) strcopy("やせすぎ",S);else strcopy("標準",S);
printf("\n%sさんは,%sです。\n標準体重 =%6.1f 肥満度 = %6.1f\n",
X.Name, S,S_Weight, Fat);
printf("\n");
return 0;
}
(3) 構造体の例(体重の平均)
#include "stdafx.h"
#define SIZE_OF_ARRAY 8
struct physique_data /*体格データ*/
{
char Name[30];
float Weight,Height;
} dt[]={
{"佐 多 憲 二",65,171},
{"村 瀬 真",57,169},
{"大 田 和 夫",60,168},
{"北 田 洋 一",73,172},
{"志 村 康 司",62,170},
{"別 府 拓 哉",59,165},
{"相 馬 修 一",68,176},
{"木 田 裕 也",61,167}
};
int main(int argc, char* argv[])
{ int i;
printf("\n");
for(i=0;i<SIZE_OF_ARRAY;i++){
printf(" %s : 体重 = %5.1f kg 身長 = %5.1f cm\n",
dt[i].Name, dt[i].Weight, dt[i].Height);
}
double T1=0,T2=0;
for(i=0;i<SIZE_OF_ARRAY;i++) {
T1 += dt[i].Weight;T2 += dt[i].Height;
}
T1 /= SIZE_OF_ARRAY; T2 /= SIZE_OF_ARRAY;
printf("\n 平均体重 = %6.2f kg 平均身長 = %6.2f cm\n\n",T1, T2);
return 0;
}
(4) 構造体の例(複素数)
#include "stdafx.h"
#include "stdlib.h"
#include "math.h"
struct Complex
{
double R; // 実部
double I; // 虚部
};
struct Complex setComplex(double R,double I)
{
Complex
X; X.R=R; X.I=I;
return
X;
}
struct Complex addComplex(struct Complex a, struct Complex b)
{
Complex X; X.R = a.R+b.R; X.I=a.I+b.I;
return
X;
}
struct Complex subComplex(struct Complex a, struct Complex b)
{
Complex
X; X.R = a.R - b.R; X.I = a.I - b.I;
return
X;
}
void printComplex(struct Complex a)
{
if(fabs(a.I)<0.0001) printf("%7.4f",a.R);
else if(fabs(a.R)<0.0001) printf("%7.4f
j",a.I);
else
if(a.I<0) printf("%7.4f - %7.4f j",
a.R, -a.I);
else
printf("%7.4f + %7.4f j",a.R, a.I);
}
int main(int argc, char* argv[])
{
Complex X1 =
setComplex(1.0,2.0);
Complex X2 =
setComplex(3.0,4.0);
Complex X3 = addComplex(X1,
X2);
Complex X4 = subComplex(X1,
X2);
printf("\n\n");
printf("
X1 = ");printComplex(X1);
printf("
X2 = ");printComplex(X2);
printf("\n\n");
printf("
X3 = ");printComplex(X3);
printf("
X4 = ");printComplex(X4);
printf("\n\n");
return 0;
}