C++を用いた配列操作:最大値除外、平均算出、配列比較の実装手法

最大値と異なる数値の総和を求める

与えられた整数列の中から最大値を特定し、その最大値と一致しない要素のみを抽出して合計を算出するプログラムの実装です。

実装コード

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    int elementCount;
    if (!(std::cin >> elementCount)) return 0;

    std::vector<int> sequence(elementCount);
    for (int i = 0; i < elementCount; ++i) {
        std::cin >> sequence[i];
    }

    // 数列内の最大値を取得
    int maxValue = *std::max_element(sequence.begin(), sequence.end());

    long long sumExcludingMax = 0;
    for (int value : sequence) {
        if (value != maxValue) {
            sumExcludingMax += value;
        }
    }

    std::cout << sumExcludingMax << std::endl;
    return 0;
}

平均値の算出と基準値を超えるデータの抽出

複数のデータ(成績など)を入力として受け取り、その平均値を小数点以下3位まで出力します。その後、平均値を上回るデータのみを元の順序で出力する処理を行います。

実装コード

#include <iostream>
#include <vector>
#include <iomanip>

int main() {
    int n;
    std::cin >> n;

    std::vector<int> dataList(n);
    double totalSum = 0;

    for (int i = 0; i < n; ++i) {
        std::cin >> dataList[i];
        totalSum += dataList[i];
    }

    double average = totalSum / n;

    // 平均値を小数点第3位まで表示
    std::cout << std::fixed << std::setprecision(3) << average << std::endl;

    // 平均を超える値を出力
    for (int val : dataList) {
        if (val > average) {
            std::cout << val << std::endl;
        }
    }

    return 0;
}

2つの配列間の要素別比較と勝敗判定

同じ長さ(10個)を持つ2つの配列 A と B の各要素をインデックスごとに比較し、「A[i] > B[i]」「A[i] == B[i]」「A[i] < B[i]」がそれぞれ何回発生したかをカウントします。最終的に、優勢な要素が多い方の配列を判定します。

実装コード

#include <iostream>
#include <vector>

int main() {
    const int SIZE = 10;
    std::vector<int> vecA(SIZE), vecB(SIZE);

    for (int i = 0; i < SIZE; ++i) std::cin >> vecA[i];
    for (int i = 0; i < SIZE; ++i) std::cin >> vecB[i];

    int winA = 0, draw = 0, winB = 0;

    for (int i = 0; i < SIZE; ++i) {
        if (vecA[i] > vecB[i]) {
            winA++;
        } else if (vecA[i] == vecB[i]) {
            draw++;
        } else {
            winB++;
        }
    }

    // 各カウントの出力
    std::cout << winA << " " << draw << " " << winB << std::endl;

    // 総合判定の出力
    if (winA > winB) {
        std::cout << "a>b" << std::endl;
    } else if (winA < winB) {
        std::cout << "a<b" << std::endl;
    } else {
        std::cout << "a=b" << std::endl;
    }

    return 0;
}

タグ: cpp Algorithm Array Vector

5月30日 15:39 投稿