2016-07-28 233 views
0

我寫了一些代碼,打印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; 
} 
+0

爲什麼不是fml = a [0] -a [size-1]? – aichao

回答

-1

如果你已經有數組的大小,你知道數組是完全填充:

int firstMinusLast (int a[ ], int size){ 
     return a[0] - a[size - 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那麼它並不重要你做減法的方式。

相關問題