#include <iostream>
#include "wow.h"
usingnamespace std;
int main()
{
double x[5];
int n = 5;
for (int i = 0; i < 5; i++)
{
x[i] = (double)rand() / RAND_MAX*(501.5 - 498.5) + 498.5;
cout << x[i] << endl; //(add a // in the begining of this line to not show random numbers)
}
int UValue;
cout << "Enter an integer: " << endl;
cin >> UValue;
sort(x, n);
int result = binarySearch(x, n, UValue);
if (result >= 0)
{
cout << "The number " << x[result] << " was found at the ""element with index " << result << endl;
}
else
{
cout << "The number " << UValue << " was not found. " << endl;
}
system("pause");
}
The problem is even if I inputted a number that I directly got from the output of random numbers it outputs [number] not found
Do you know that you really shouldn't compare floating point numbers for equality? Floating point numbers are approximations and can have various round off type of problems.
Oh really? and No I did not, it was never discussed in class. Does that mean that I have to add a way to find the number within a specific percent error or something?
> Does that mean that I have to add a way to find the number within a specific percent error or something?
That is one way of doing it: compare for equality with a tolerence.
The other possibility is to write the binary search using less than < and greater than > operators. This would imply that the comparison for equality is exact (between representable values):
for example searching for 0.0100000000001 won't find 0.01
1 2 3 4 5 6 7 8 9 10
std::size_t bsearch( constdouble a[], std::size_t low, std::size_t high, double value )
{
if( low > high ) return std::size_t(-1) ; // return -1 cast to std::size_t if not found
const std::size_t mid = low + (high - low) / 2 ;
if( value < a[mid] ) return bsearch( a, low, mid-1, value ) ;
elseif( value > a[mid] ) return bsearch( a, mid+1, high, value ) ;
elsereturn mid ; // return the position within the array if found
}