473,386 Members | 1,803 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

Switch (expression) does not work with Float types

Hi,

Can anyone tell me why this does not work:

---------------------------------------------

float b = 2.51F;

switch(b)
{
case 2.51F:
Console.WriteLine("A");
break;
default:
break;
}

Error: A value of an integral type expected

---------------------------------------------

It fails on the switch statement and does not go any further.

Any help is much appriciated.

Thanks,
Sivas
Nov 16 '05 #1
8 24745
> Can anyone tell me why this does not work:

---------------------------------------------

float b = 2.51F;

switch(b)
{
case 2.51F:
Console.WriteLine("A");
break;
default:
break;
}

Error: A value of an integral type expected


Because floating points tend do be less accurate than integers and might
shift a little dependin on the used processor it runs on and the generated
assembler code. floats are not a accurate number.

In theory you assign 2.51000000..... and compare with 2.51000000.....
according to your example, but in reality the internal saved registery
number might be ranging between 2.50999998..... 2.51000011..... depending on
the generated code of the compiler.

A tip: if you compare floats or doubles, always compare if the value is
between 2 minimum and maximum ranges (error).
This is why accounting software tend to store nubers with digits als integer
by multiplying by 100 and later get it back by dividing by 100.

I hope this helps?

--
http://www.skyscan.be
Nov 16 '05 #2
On 19 Oct 2004 05:41:40 -0700, si***@webtraveller.com.au (Sivas)
wrote:
Hi,

Can anyone tell me why this does not work:

---------------------------------------------

float b = 2.51F;

switch(b)
{
case 2.51F:
Console.WriteLine("A");
break;
default:
break;
}

Error: A value of an integral type expected

---------------------------------------------

It fails on the switch statement and does not go any further.


You can't use floats in a switch
integers and string only.

This is because
2.51F may not equal 2.51F at any given time
one of them may be 2.51000000000001

If you want this then you need to decide on the level of precision you
want and treat it as an integer

something like this should work
switch( (int)(b*100) )
{
case 251:
}

Vin
Nov 16 '05 #3
Sivas <si***@webtraveller.com.au> wrote:
Can anyone tell me why this does not work:

---------------------------------------------

float b = 2.51F;

switch(b)
{
case 2.51F:
Console.WriteLine("A");
break;
default:
break;
}

Error: A value of an integral type expected

---------------------------------------------

It fails on the switch statement and does not go any further.


From the ECMA spec, section 15.7.2:

<quote>
The governing type of a switch statement is established by the switch
expression. If the type of the switch expression is sbyte, byte, short,
ushort, int, uint, long, ulong, char, string, or an enum-type, then
that is the governing type of the switch statement. Otherwise, exactly
one user-defined implicit conversion (§13.4) must exist from the type
of the switch expression to one of the following possible governing
types: sbyte, byte, short, ushort, int, uint, long, ulong, char,
string. If no such implicit conversion exists, or if more than one such
implicit conversion exists, a compile-time error occurs.
</quote>

Using floating point numbers in a switch statement would just be asking
for trouble, even if you could do it, due to the nature of floating
point and the dangers of equality comparisons.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #4
Sivas,

I would think that it has to do with the fact that the float type can
not represent exact values (which is really what you need for a switch
statement). I mean, how would you handle it? Would any value that differs
by Epsilon be allowed? It's not the kind of guesswork that the language
designers or a developer should have to deal with.

If anything, if statements are better for this, since I think you
probably have some specific logic that you have to handle.

Hope this helps.

--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Sivas" <si***@webtraveller.com.au> wrote in message
news:1d**************************@posting.google.c om...
Hi,

Can anyone tell me why this does not work:

---------------------------------------------

float b = 2.51F;

switch(b)
{
case 2.51F:
Console.WriteLine("A");
break;
default:
break;
}

Error: A value of an integral type expected

---------------------------------------------

It fails on the switch statement and does not go any further.

Any help is much appriciated.

Thanks,
Sivas

Nov 16 '05 #5
Hi,

Thank you all for your expert answers. I stand before you all, much
the wiser!

Since I do have to use a 2 decimal precision number, I will go with
the suggested work around and multiply by a hundred. Thats slick,
actually!

Thanks heaps,
Sivas
Nov 16 '05 #6
Be careful, young wizard :-)

2.51 * 100 converted to integer may end up being 250, because the product
was 250.99999999 rather than 251.

All the Best
Julian N.

"Sivas" <si***@webtraveller.com.au> wrote in message
news:1d**************************@posting.google.c om...
Hi,

Thank you all for your expert answers. I stand before you all, much
the wiser!

Since I do have to use a 2 decimal precision number, I will go with
the suggested work around and multiply by a hundred. Thats slick,
actually!

Thanks heaps,
Sivas

Nov 16 '05 #7
Julian Nicholls schrieb:
2.51 * 100 converted to integer may end up being 250, because the product
was 250.99999999 rather than 251.


Just add 0.5 to the product before explicit conversion and you get
mathematically correct rounding.

Christian
Nov 16 '05 #8
Or, just use the Decimal type. It will prevent the need for hacks such
as adding .5. Just declare the 2.50 as a decimal, perform the
multiplication, and then cast to an integer.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Christian Gudrian" <us****@gudrian.de> wrote in message
news:qk**************@news.gudrian.de...
Julian Nicholls schrieb:
2.51 * 100 converted to integer may end up being 250, because the product
was 250.99999999 rather than 251.


Just add 0.5 to the product before explicit conversion and you get
mathematically correct rounding.

Christian

Nov 16 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: bayxarea-usenet | last post by:
I am getting the following error during compiling: 'switch expression not integral' I am new to the switch command - here is a snip of my code where I have used this.. .. what is the problem...
3
by: pgraeve | last post by:
I am a convert from VB to C# so bear with me on this "conversion" question C# switch statement seems to be the closest relative to VB's Select Case. I used VB's Select Case statement liberally. ...
4
by: Jim | last post by:
Hey all, I'm hoping someone may be able to help me. I need to evaluate some strings to see if their values are what I expect and it doesn't seem to work. Any help you can provide would be really...
27
by: Yuriy Solodkyy | last post by:
Hi VS 2005 beta 2 successfully compiles the following: using System; using System.Collections.Generic; using System.Text; namespace ConsoleApplication1 { class Program {
13
by: Fei Liu | last post by:
Hi Group, I've got a problem I couldn't find a good solution. I am working with scientific data files in netCDF format. One of the properties of netCDF data is that the actual type of data is only...
130
by: Daniel Manes | last post by:
I'm baffled. I have a column in a SQL Server Express database called "Longitude," which is a float. When I view the table in a DataGridView, some of the numbers, which only have two decimal places...
13
by: hn.ft.pris | last post by:
Hi: I have the following simple program: #include<iostream> using namespace std; int main(int argc, char* argv){ const double L = 1.234; const int T = static_cast<const int>(L); int arr;
3
by: bob_jenkins | last post by:
In C# 2.0, given an arbitrary expression and the types of the variables referenced in it, how do I find the expression type? For example, int x; float y; what is the type of x+y? If I had...
3
by: sophia.agnes | last post by:
Dear all, what are the major expression types in c? i have seen the following types of expressions 1) constant expressions 2) integral expressions 3) float expressions 4) pointer...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.