Background
So I'm making a simple game of unfair hangman in C# (there's a list of words that are valid solutions based on the information I've to the player (e.g. word length) which dwindles down over time, and the player only wins when there's only one possible solution and they've guessed all the letters).
Anyway, the important thing to know is I have a line of code that looks like this:
availableWords.RemoveAll(word => AmountInCommon(word) != lowestInCommon);
(I remove all the words from the availableWords that have more letters in common with the letters the user has guessed than the word in availableWords with the least letters in common)
The problem is that this code only works when compiler optimizations are turned off.
Demo code showcasing the problem
class Program {
static void Main() {
float randomPowerOf2 = (float)Math.Pow(2, new Random().Next(-4, 5));
float foo1 = Foo(3f); // some non power of 2
float foo2 = Foo(randomPowerOf2);
float baz = Baz();
// prints false with compiler optimizations; true without compiler optimizations
Console.WriteLine(Math.Round(Foo(3f), 2) == Math.Round(foo1, 2));
// prints true with and without compiler optimizations
Console.WriteLine(Math.Round(Foo(3f), 2) == Math.Round(foo1, 2));
// prints true with and without compiler optimizations
Console.WriteLine(Foo(randomPowerOf2) == foo2);
// prints true with and without compiler optimizations
Console.WriteLine(Baz() == baz);
Console.ReadLine();
}
static float Foo(float divisor) {
return 1 / divisor;
}
static float Baz() {
return 1 / 3f;
}
}
I assume this has something to do with how floating-point numbers work, but what confuses me is why toggling on and off compiler optimizations affects it. I'm guessing what I should do is just round the floats to 3 or so decimals of precision, since that's all I really need. Why does this happen and is my solution best-practice?
Edit:
I realized that in this case since the word length doesn't change I could just have AmountInCommon
return the integer representing how many letters are in common instead of a float that represents the ratio of letters in common to word length. Your answers are still helpful though.