C++関数とモジュールの実践演習

7.12 復習問題

1. 関数の宣言、定義、呼び出しの順序について説明せよ

2. 以下の関数プロトタイプを作成せよ a. void igor(); b. float tofu(int n); c. double mpg(double d1, double d2); d. long summation(long data[], int size); e. double doctor(const string s); f. void ofcourse(boss b); g. string plot(map *m);

3. 配列要素を指定値で初期化する関数

void initializeArray(int data[], int size, int val) {
    for (int index = 0; index < size; index++) {
        data[index] = val;
    }
}

4. ポインタ範囲の要素を設定する関数

void setRange(int* start, int* end, int val) {
    for (int* ptr = start; ptr != end; ptr++) {
        *ptr = val;
    }
}

5. 配列の最大値を取得する関数

double findMaximum(double values[], int count) {
    double maxVal = values[0];
    for (int i = 1; i < count; i++) {
        if (values[i] > maxVal) {
            maxVal = values[i];
        }
    }
    return maxVal;
}

6. 基本型引数は値渡しのためconstが不要だが、ポインタ引数はアドレスを直接操作するためconstで保護する必要がある

8. 文字列内の文字を置換する関数

int replaceCharacters(char* str, char from, char to) {
    int count = 0;
    while (*str) {
        if (*str == from) {
            *str = to;
            count++;
        }
        str++;
    }
    return count;
}

9. 文字列リテラルの特定文字アクセス a. *"pizza" → 'p' b. "taco"[2] → 'c'

11. 関数ポインタを引数に取る関数

int process(int (*funcPtr)(const char *)) {
    // 処理実装
}

12. 構造体の表示関数

void displayApplicant(applicant app) {
    cout << app.name << endl;
    for (int i = 0; i < 3; i++) {
        cout << app.credit_rating[i] << endl;
    }
}

void displayApplicantPtr(applicant* appPtr) {
    cout << appPtr->name << endl;
    for (int i = 0; i < 3; i++) {
        cout << appPtr->credit_rating[i] << endl;
    }
}

13. 関数ポインタの型定義

void processApp(applicant *a);
const char* compareApps(const applicant *a1, const applicant *a2);

typedef void (*AppProcessor)(applicant*);
typedef const char* (*AppComparator)(const applicant*, const applicant*);
AppProcessor processor = processApp;
AppComparator comparator = compareApps;
AppProcessor processors[5];
AppComparator (*comparatorArray)[10];

7.13 プログラミング演習

1. 調和平均計算

#include<iostream>
using namespace std;

double harmonicMean(double a, double b) {
    return 2.0 * a * b / (a + b);
}

int main() {
    double num1, num2;
    while (true) {
        cout << "2つの数値を入力:";
        cin >> num1 >> num2;
        if (num1 == 0 || num2 == 0) break;
        cout << harmonicMean(num1, num2) << endl;
    }
    return 0;
}

2. 配列入力処理

#include<iostream>
using namespace std;

const int MAX_SIZE = 10;

int inputScores(double scores[], int max) {
    int count = 0;
    while (count < max) {
        cout << "スコア入力: ";
        cin >> scores[count++];
        cout << "終了する場合は 'q' を入力: ";
        if (cin.get() == 'q') break;
    }
    return count;
}

void outputScores(double scores[], int count) {
    for (int i = 0; i < count; i++) {
        cout << scores[i] << " ";
    }
    cout << endl;
}

double calculateAverage(double scores[], int count) {
    double total = 0;
    for (int i = 0; i < count; i++) {
        total += scores[i];
    }
    return total / count;
}

int main() {
    double scoreArray[MAX_SIZE];
    int count = inputScores(scoreArray, MAX_SIZE);
    outputScores(scoreArray, count);
    cout << "平均: " << calculateAverage(scoreArray, count) << endl;
    return 0;
}

3. 構造体操作

#include<iostream>
using namespace std;

struct Container {
    char maker[40];
    float height;
    float width;
    float depth;
    float volume;
};

void displayContainer(Container cont) {
    cout << cont.maker << endl
         << cont.height << endl
         << cont.width << endl
         << cont.depth << endl
         << cont.volume << endl;
}

void calculateVolume(Container* contPtr) {
    contPtr->volume = contPtr->height * contPtr->width * contPtr->depth;
}

int main() {
    Container box = {"Example", 10, 8, 5};
    displayContainer(box);
    calculateVolume(&box);
    displayContainer(box);
    return 0;
}

4. 確率計算関数

#include<iostream>
using namespace std;

long double calculateProbability(unsigned total, unsigned special, unsigned picks) {
    long double result = 1.0;
    for (unsigned i = 0; i < picks; i++) {
        result = result * (total - i) / (picks - i);
    }
    return result / special;
}

int main() {
    unsigned total, special, picks;
    cout << "選択肢総数、特別数、選択数を入力:";
    while (cin >> total >> special >> picks && picks <= total) {
        cout << "当選確率: " << calculateProbability(total, special, picks) << endl;
        cout << "次の3数値(qで終了):";
    }
    return 0;
}

5. 階乗計算

#include<iostream>
using namespace std;

int computeFactorial(int n) {
    int result = 1;
    for (; n > 1; n--) {
        result *= n;
    }
    return result;
}

int main() {
    int num;
    cout << "数値を入力:";
    cin >> num;
    cout << num << "! = " << computeFactorial(num) << endl;
    return 0;
}

6. 配列入出力関数

#include<iostream>
using namespace std;

int fillArray(double arr[], int limit) {
    int count = 0;
    double value;
    while (count < limit && cin >> value) {
        arr[count++] = value;
        cout << "次を入力(qで終了): ";
    }
    return count;
}

void displayArray(double arr[], int size) {
    for (int i = 0; i < size; i++) {
        cout << arr[i] << endl;
    }
}

int main() {
    const int SIZE = 5;
    double data[SIZE];
    int count = fillArray(data, SIZE);
    displayArray(data, count);
    return 0;
}

7. ポインタ範囲を使用した配列操作

#include<iostream>
using namespace std;

double* inputValues(double* start, double* end) {
    double* ptr = start;
    while (ptr != end) {
        cout << "値を入力: ";
        if (!(cin >> *ptr)) break;
        ptr++;
    }
    return ptr;
}

void outputValues(double* start, double* end) {
    for (double* ptr = start; ptr != end; ptr++) {
        cout << *ptr << endl;
    }
}

void adjustValues(double factor, double* start, double* end) {
    for (double* ptr = start; ptr != end; ptr++) {
        *ptr *= factor;
    }
}

int main() {
    const int MAX = 5;
    double values[MAX];
    double* end = inputValues(values, values + MAX);
    outputValues(values, end);
    double factor;
    cout << "調整係数: ";
    cin >> factor;
    adjustValues(factor, values, end);
    outputValues(values, end);
    return 0;
}

8. 季節支出管理

#include<iostream>
using namespace std;

const int SEASONS = 4;
const char* SEASON_NAMES[] = {"春", "夏", "秋", "冬"};

void inputExpenses(double expenses[]) {
    for (int i = 0; i < SEASONS; i++) {
        cout << SEASON_NAMES[i] << "の支出: ";
        cin >> expenses[i];
    }
}

void displayExpenses(double expenses[]) {
    double total = 0;
    cout << "\n支出報告\n";
    for (int i = 0; i < SEASONS; i++) {
        cout << SEASON_NAMES[i] << ": " << expenses[i] << endl;
        total += expenses[i];
    }
    cout << "総支出: " << total << endl;
}

int main() {
    double seasonalExpenses[SEASONS];
    inputExpenses(seasonalExpenses);
    displayExpenses(seasonalExpenses);
    return 0;
}

タグ: C++ 関数 ポインタ 配列 構造体

6月13日 22:51 投稿