Cannot implicitly convert type 'double' to 'bool'

D

Doug

Hi

I have a short piece of trial code that compares some input and then
produces a message based on the value.

However I get a build error that i dont know how to resolve ' Cannot
implicitly convert type 'double' to 'bool'

The code is

double expect = int.Parse(txtInput.Text);


if (expect <100) MessageBox.Show("This is less than 100");

else if (expect = 100) MessageBox.Show("This is equal to 100");

else MessageBox.Show("This is greater than 100","Result");

}

}

The error relates to the 'else if' line.



Please advise what the error means and how to resolve it.



Thanks

Doug
 
O

Octavio Hernandez

HI Doug,

The problem is you're using an assignment operator (=) instead of an
equality comparison operator (==) in:

if (expect = 100) // should be '=='

Regards,

Octavio
 
L

Lucian Wischik

Doug said:
double expect = int.Parse(txtInput.Text);
...
else if (expect = 100) MessageBox.Show("This is equal to 100");

That looks very dodgy. You should never compare whether one floating
point number is equal to another (unless one of them is 0 or 1).
 
?

=?ISO-8859-1?Q?G=F6ran_Andersson?=

The reason is simply that a floating point number often contains a
number that is approximately what you stored in it. If you do:

double x = 3;

The variable x probably contains something like 2.99999999999999999 or
3.000000000000001 rather than the exact value 3. If you now compare this
"almost 3" to the value of some other variable that is "almost 3", the
result is rather unpredictable.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top