【问题标题】:how to print the minimum number of an array and its index calling them with a function?如何打印数组的最小数量及其使用函数调用它们的索引?
【发布时间】:2019-04-30 03:36:24
【问题描述】:

我知道要制作这个函数我需要使用 void 类型,这是我的代码。请有人告诉我如何使用 void 类型制作它并在 main 中调用它,我尝试过这样做,但我最新的事情失败了到达是只返回数组的最小个数

#include <iostream>
using namespace std;
int min(int arr[], int size)
{

    int small=arr[0];
    for(int i=0; i<size; i++)
        if(arr[i]<small)
            small=arr[i];
        return small;
}

int main()
{
    int size;
    cin>>size;
   int X[size];
   for(int i=0; i<size; i++)
    cin>>X[i];

 cout<<"Min num in the array = " << min(X,size) <<endl;


    return 0;
}

【问题讨论】:

  • 如果函数无法返回值,您需要为此使用引用。
  • auto ptr = std::min_element(X, X + size); std::cout &lt;&lt; "min = " &lt;&lt; *ptr &lt;&lt; " index = " &lt;&lt; std::distance(X, ptr);
  • 请注意,在标准c++ 中这是非法的:int X[size]; 因为size 必须是编译时间常数,

标签: c++ arrays function


【解决方案1】:

选项 1

在通过引用传递的参数中返回它。

void min(int arr[], int& index)
{
   ...
}

并将函数用作

int index = 0;
min(X, index);
cout << "The index of the min in the array = " << index << endl;
cout << "Min num in the array = " << X[index] << endl;

选项 2

改变返回类型,返回索引。

int min(int arr[])
{
   int index = 0;
   ...
   return index;
}

并将函数用作

int index = min(X);
cout << "The index of the min in the array = " << index << endl;
cout << "Min num in the array = " << X[index] << endl;

【讨论】:

    猜你喜欢
    • 2016-11-05
    • 1970-01-01
    • 2012-01-09
    • 1970-01-01
    • 1970-01-01
    • 2016-02-24
    • 2017-10-01
    • 2022-11-24
    相关资源
    最近更新 更多