第3回演習:解答例


(1)実数a,bを入力すると,a^bを計算し画面に出力するプログラムを作成せよ.
ヒント:べき乗を計算するには,pow 関数を使用する.


#include<stdio.h>
#include<math.h>

void main()
{
    double a, b, bekijou;

    printf("a=");
    scanf("%lf", &a);
    printf("b=");
    scanf("%lf", &b);

    bekijou = pow(a, b);

    printf("a^bは,%lfです。¥n",bekijou);
}

(2)キーボードから長方形の二辺の長さを入力し面積を求める関数に渡すと,面積を戻す関数を作成し,結果を表示せよ.
ヒント:引数は2つ,戻り値は1つ.長さ,面積は整数型で定義しなさい.


#include<stdio.h>

int menseki(int c, int d)
{
    int x;

    x = c*d;

    return x;
}

void main()
{
    int a, b, answer;

    printf("a=");
    scanf("%d", &a);
    printf("b=");
    scanf("%d", &b);

    answer = menseki(a, b);

    printf("長方形の面積は%dです。¥n",answer);
}

(3)整数型の2つの数値の最小値を返す関数を作成し,キーボードから入力した整数の最小値を表示せよ.


#include<stdio.h>

int saishouchi(int c, int d)
{
    int x;

    if(c<d){
	x = c;
    } else{
	x = d;
    }

    return x;
}

void main()
{
    int a, b, answer;

    printf("a=");
    scanf("%d", &a);
    printf("b=");
    scanf("%d", &b);

    answer = saishouchi(a, b);

    printf("2つの数値の最小値は%dです。¥n",answer);
}

(4)自然数 n の階乗 n! を求めるプログラムを,関数を用いて作成せよ.但し,0! = 1 である.(注:C言語では「!」は否定を表す演算子)
ヒント:まず作成する関数の引数の「型」と「個数」,戻り値の「有無」,「型」を検討しよう.


#include<stdio.h>

int kaijou(int a)
{
    int x, i;

    x = 1;

    for(i=1;i<=a;i++){
	x *= i;
    }

    return x;
}

void main()
{
    int n, answer;

    printf("自然数n=");
    scanf("%d", &n);

    answer = kaijou(n);

    printf("n!は%dです。¥n",answer);
}

(5)上の関数を利用して,キーボードから自然数 n, r を入力すると,n 枚のカードから r 枚選ぶ組み合わせの数を求めるプログラムを作成せよ.
ヒント:(1)まず, n >= r である必要がある.(2) nCr = n! / (n-r)! r!


#include<stdio.h>

int kaijou(int a)
{
    int x, i;

    x = 1;

    for(i=1;i<=a;i++){
	x *= i;
    }

    return x;
}

void main()
{
    int n, r, answer;

    printf("自然数n=");
    scanf("%d", &n);
    printf("自然数r=");
    scanf("%d", &r);

    if(n>=r){
    	answer = kaijou(n)/kaijou(n-r)/kaijou(r);
    	printf("n枚のカードからr枚選ぶ組合せの数は%dです。¥n",answer);
    } else{
		printf("入力エラーです。¥n");
    }
}