首先减去数组

时间:2016-07-28 01:15:39

标签: c++ arrays

我编写了一些代码,可以在3到7之间打印25个随机数,然后将它们放入一个数组中,然后放入其反向数组。我现在如何减去数组中的第一个数字减去数组中的最后一个数字?到目前为止,这是我的代码。我有函数调用和原型制作;只是不确定准确地在定义中放入什么:

#include <time.h>
#include <iostream>
#include <stdlib.h>
using namespace std;

// Function prototypes
void showArray ( int a[ ], int size ); // shows the array in the format "int a [ ] = { 3, 7, 4, ... ,5, 6, 3, 4, 7 } "
void showBeforeIndex( int a [ ], int size, int index); // shows all array values before a specified index
int firstMinusLast ( int a[ ], int size );
// **************************************************************************************************************************************
int main ()
{
// Array and reverse array
    srand((int)time(NULL));
    int i=0;
    const int SIZE = 25;
    int randvalue[SIZE];


    cout << "Making an array of 25 random integers from 3 to 7!" << endl;

    for(; i < SIZE; i++)
    {
    randvalue[i] = rand () % 5 + 3; // random number between 3 to 7
    }
    cout << "Original array a [ ] = {";
    showArray(randvalue, SIZE);
    cout << "}" << endl;

    int j = SIZE-1;
    i = 0;

    while( i <= j)
    {
        swap(randvalue[i], randvalue[j]);
        i++;
        j--;
    }
    cout << "Reversed array a [ ] = {";
    showArray(randvalue, SIZE);
    cout << "}" << endl;
// *******************************************************************************************************
// Function call for FIRST - LAST
    int returnFirstLast = firstMinusLast (randvalue, 25);
    cout << "The difference between the first and and last array elements is " << returnFirstLast << endl;
//********************************************************************************************************


    return 0;
}

// Function definition for ARRAY
void showArray ( int a[ ], int size )
{
    int sum = 0;
    for(int i = 0; i < size; i++)
        cout << a[i];
}


// Function definition for FIRST - LAST
int firstMinusLast ( int a[ ], int size )
{
    int fml;




    return fml;
}

2 个答案:

答案 0 :(得分:-1)

如果您已经拥有数组的大小,并且您知道数组已完全填充:

    int firstMinusLast ( int a[ ], int size ){
         return a[0] - a[size - 1];
    }

答案 1 :(得分:-1)

在C / C ++中,数组从0开始索引。所以第一个元素在索引0处。假定数组的第一个元素在索引0处,那么数组的最后一个元素的索引等于数组的大小减1.代码:

第一个元素是a[0]

最后一个元素是a[SIZE - 1]

为了得到他们的不同:fml你只需写下:fml = a[0] - a[SIZE - 1]

对于一个函数来说这似乎很简单,所以也许你期望更大或更不一样的东西。

你需要差异的绝对值吗?没有标志的变化幅度?如果是这样,只需使用绝对值函数。

fml = abs(a[0] - a[SIZE-1]);

如果你想在反向之前说你想要第一个减去最后一个,那么就这样做:

fml = a[SIZE-1] - a[0];

如果它需要abs,那么减去哪种方式并不重要。

相关问题