C++一维数组程序编写

编写程序在一个一维数组中存放十个正整数,求最大值,并与最后一个数交换。

参考如下:

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

int main()
{
    int a[10];
    int i, maxIndex = 0, t;
    for (i = 0; i < 10; i++)
    {
        scanf("%d", &a[i]);
        if (a[i] > a[maxIndex])
            maxIndex = i;
    }

    t = a[9];
    a[9] = a[maxIndex];
    a[maxIndex] = t;

    for (i = 0; i < 10; i++)
        printf("%d ", a[i]);

    return 0;
}

以下是使用 C++ 编写的程序,可以在一个一维数组中存储十个正整数,并找到最大值,然后将其与数组的最后一个数进行交换:

#include <iostream>
using namespace std;

int main() {
    int arr[10];
    int max_val = 0;
    int max_index = 0;

    // 读取十个正整数并找到最大值
    for (int i = 0; i < 10; i++) {
        cin >> arr[i];
        if (arr[i] > max_val) {
            max_val = arr[i];
            max_index = i;
        }
    }

    // 将最大值与数组的最后一个数进行交换
    int temp = arr[9];
    arr[9] = max_val;
    arr[max_index] = temp;

    // 输出交换后的数组
    for (int i = 0; i < 10; i++) {
        cout << arr[i] << " ";
    }

    return 0;
}

在这个程序中,我们首先定义一个大小为 10 的整型数组 arr,然后使用 cin 读取十个正整数,并找到最大值以及最大值所在的索引。然后,我们使用一个临时变量 temp 将数组的最后一个数存储起来,将最大值存储到数组的最后一个位置,并将 temp 存储到最大值所在的索引位置。最后,我们使用 cout 输出交换后的数组。