473,804 Members | 2,194 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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.WriteLi ne("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 24801
> Can anyone tell me why this does not work:

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

float b = 2.51F;

switch(b)
{
case 2.51F:
Console.WriteLi ne("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***@webtravel ler.com.au (Sivas)
wrote:
Hi,

Can anyone tell me why this does not work:

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

float b = 2.51F;

switch(b)
{
case 2.51F:
Console.WriteLi ne("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.5100000000000 1

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***@webtrave ller.com.au> wrote:
Can anyone tell me why this does not work:

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

float b = 2.51F;

switch(b)
{
case 2.51F:
Console.WriteLi ne("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.co m>
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.co m

"Sivas" <si***@webtrave ller.com.au> wrote in message
news:1d******** *************** ***@posting.goo gle.com...
Hi,

Can anyone tell me why this does not work:

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

float b = 2.51F;

switch(b)
{
case 2.51F:
Console.WriteLi ne("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***@webtrave ller.com.au> wrote in message
news:1d******** *************** ***@posting.goo gle.com...
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.co m

"Christian Gudrian" <us****@gudrian .de> wrote in message
news:qk******** ******@news.gud rian.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
18218
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 here? Thanks! ------------- snip -------------------------- for (ii = 0; ii < n; ii++)
3
19743
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. Now I find myself wanting to use "Select Case" i.e., "switch" in C# regularly, but I always have to find another way b/c C#'s switch statement only allows static or integral variables. For example, I often want to use a switch statement based on the...
4
13287
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 appreciated. Here is my non-working syntax: switch(true) { case Header.ParentSectionDisplayName == String.Empty: MyString = Header.SectionDisplayName;
27
5641
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
4538
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 known at run time. Therefore a lot of template based trick isn't too useful. Considering datafile float x(3) 3.5, 2.5, 8.9 double y(3) 2.7, -2.3, 1.2 int z(3) 5, 2, 3
130
6648
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 in the database show up with *15* decimal places and are ever so slightly off (in the example in the subject line, by about 2E-15). I'm not doing any operations on this column. It's just running a stored procedure which performs a pretty basic...
13
27445
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
1752
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 values for x and y, I could do (x+y).GetType(). But I don't, I just have their types. Default values won't work because values that don't cause the expression to raise an error might be very hard
3
2390
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 expressions
0
9715
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9595
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10603
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10353
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10356
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10099
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6869
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5536
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5675
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.