簡體   English   中英

C++ 程序將用戶的十個數字放入一個數組並使用指針按順序對數組進行排序

[英]C++ program than takes ten numbers from user into an array and sorts the array in order, using pointers

編寫一個程序,要求用戶輸入 10 個正數 integer 數字,將它們存儲在一個數組中,然后用最小數字替換第一個元素,用最大數字替換最后一個元素。

您必須編寫 3 個函數:

  1. void getNumber(int *):輸入 10 個正 integer 數字並將它們存儲在一個數組中。

  2. void minMax(int *):找到最小和最大數,並重新排列數組。

  3. printNumber(int *):打印生成的新數組。

筆記:
您必須使用 POINTERS 訪問所有函數中的數組(未使用指針將導致 50% 的扣除)。

它可以工作,但我需要現在main的用戶輸入部分,也是它自己的 function。 我不知道該怎么做!

#include <iostream>
using namespace std;

// Function to sort the numbers using pointers 
void sort(int n, int* ptr)
{
    int i, j, t;

    // Sort the numbers using pointers 
    for (i = 0; i < n; i++) {
        for (j = i + 1; j < n; j++) {
            if (*(ptr + j) < *(ptr + i)) {
                t = *(ptr + i);
                *(ptr + i) = *(ptr + j);
                *(ptr + j) = t;
            }
        }
    }
}

int print(int n, int *ptr) 
{
    for (int i = 0; i < n; i++)
        cout << *(ptr + i) << " " ;
    cout << endl;
    return *ptr + 1;
}

int main()
{
    //int n = 10;
    //int arr[] = { 0, 4, 74, 88, 12, 37, 12, 7, 65, 2 };

    const int SIZE = 10;
    int values[SIZE];
    int i;
    //user input
    cout << "Enter 10 numbers: ";
    for (i = 0; i < 10; ++i)
        cin >> values[i];
    //prints forward array
    cout << "You entered: ";
    for (i = 0; i < 10; ++i)
        cout << values[i] << " ";
    cout << endl;

    sort(i, values);
    cout << "The numbers in order are: ";
    print(i, values);

    system("pause");
    return 0;
}

這是將用戶輸入分解為單獨的 function 的代碼:

void FillInArrayFromInput(int* arr, int size) // take the pointer to first element of the array and the size
{
    cout << "Enter 10 numbers: ";
    for (int i = 0; i < size; ++i)
        cin >> arr[i]; // Edit: there was little typo here!
}

現在主要的 function 將是:

int main()
{
    const int SIZE = 10;
    int values[SIZE];

    //user input
    FillInArrayFromInput(values, SIZE);

    //prints forward array
    cout << "You entered: ";
    for (i = 0; i < 10; ++i)
        cout << values[i] << " ";
    cout << endl;

    sort(i, values);
    cout << "The numbers in order are: ";
    print(i, values);

    system("pause");
    return 0;

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM