Finding the minimum number

I'm having a trouble testing my code. The point is to enter an array of numbers and for the code to find the smallest one. It's compiling just fine, but the testing isn't working out so well.

Here's the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
double FindMinValue(double num2[], int size2)
{
  double min;
    for (int i=1;  i < size2;  ++i)
      if (num2[i] < min)
      {
        min = num2[i];
      }
  return min;
}
 
int main()
{
  const int size2=4;
  int i = 4;
  double number2[i];
  double small;
  for (size_t i = 0; i < sizeof(number2) / sizeof(number2[0]); i++)
  {
    cin >> number2[i];
  }
  small = FindMinValue(number2, size2);
  std::cout << small;
}


And here's the output from the test:

1
2
3
4
5
6
$ ./test
4
2
7
5
1.4822e-323
Last edited on
you haven't initialized min in FindMinValue. It should be num2[0], if size2 > 0. You'll have to find some return value if size2 < 1.
To clarify, I need to make an if statement and the value of min relies on that if statement? Or did I misread that?
1
2
3
4
5
6
7
8
9
#include <iostream>
using namespace std;
int main(){	
	int arr[5] = {4,2,5,8,3};
	int min =arr[0];
	for(int x: arr)	if(x<min) min =x;	
	cout << "smallest = " << min << endl;	
return 0;
}
Your test function ...

Line 14 defines size2, which is only used on line 22.

Line 16 uses i for the size of array. The i is not const, nor has it any connection to size2.

Line 18 defines a new i that masks the i of the outer scope. Curiously, this i is unsigned while the other i and size2 are signed. Considering the purpose of the variables one would expect all of them to be unsigned.

Line 18 calculates the size of the array. That is fine and dandy, but the size of array is stored in the (now invisible) variable that was set on line 15 and used on line 16.

Line 22 the size2, being set separately, could be larger than the array. That would be an error.
Thanks for the help guys, and thanks for the code, but I'm limited to using C++98, unfortunately.
Topic archived. No new replies allowed.