change the int i = 1 to int i = 0 |
it shouldnt be. As it is just skipping the first element check, as it was already assigned to smallest for intital check and thus checking against itself if it was 0.
I am not sure why, but you cannot get the size of the array in the function, so i instead just pasded the size to it. Although if there was a way to find the size in a function, i would prefer that method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
#include <iostream>
using namespace std;
int min(int a[], int ind){
int smallest = a[0];
for ( int i=1; i < ind; ++i )
//cout << smallest << endl;
if ( a[i] < smallest )
smallest = a[i] ;
return smallest;
}
int main ()
{
int array []= {44, 54, -3, 3};
int ind = sizeof(array)/sizeof(array[0]);
cout << min(array, ind) << " is the smallest" << endl;
}
|
Sorry If Ive gotten this wrong, but I dont exactly know what yo are trying to do. |
I am trying to input a number that when checked against an array of random numbers, returns the number of the nearest to that number of the array. Example:
if an array had the elements 1 and 10, and i gave it the number 8, it would return 10, if i gave it the number 2, it would return the number 1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
|
#include <iostream>
#include <cmath>
using namespace std;
int min(int a[], int ind){
int smallest = a[0];
for ( int i=1; i < ind; ++i )
//cout << smallest << endl;
if ( a[i] < smallest )
smallest = a[i] ;
return smallest;
}
int main ()
{
int num = 10;
int array []= {44, 54, 3};
int ind = sizeof(array)/sizeof(array[0]);
int temp[ind];
//cout << min(array, ind) << " is the smallest" << endl;
for (int i=0; i<ind; i++){
for (int j=0; j<ind; j++){
cout << abs(array[i] - num) << endl;
temp[j] = abs(array[i] - num);
}
}
cout << min(temp, ind) << endl;
}
|
something like this, except it returns the lowest number 7, which is right, except i need the number associated with it, 3, as the number i am checking it with is 10. I am not sure if i am making it more complicated than it has to be or not? Would the easiest method be to map the element with the associated number? It seems like an awful lot for such a simple task.