About the data type FLOAT
This is a very simple pgm where i hav been tryin to divide numbers.Am confused about this.Suppose i divide a number by zero the control has to go to the exception block and display the message,but that does not happen,I get the result from Console.Writeline as:
"The ans is:Infinity
How s tis possible when i use the datatype float?I wud like to kno wats happening behind?The result is the same even when i dont use Exception.
using System;
using System.Collections.Generic;
using System.Text;
namespace floatchk
{
classProgram
{
staticvoid
Main(string
[] args){
Program p =new
Program();p.vasumathy();
}
publicvoid
vasumathy(){
float
a, b;try
{
Console.WriteLine("Enter the num to be divided");a =
Convert.ToInt32(Console.ReadLine());Console.WriteLine("Enter the divisor");b =
Convert.ToInt32(Console.ReadLine());float
c = (float
)(a / b);Console.WriteLine("The answer is:"+c);}
catch
(DivideByZeroException e){
Console.WriteLine("Sorry u cannot divide a number by zero");}
catch
(Exception e){
Console.WriteLine(e);}
}
}
}
Thanks in advance.
Yes for float numbers like float an double, they don't throw an exception on division by 0, they return (+/-)inifinity and for 0/0 -->NaN, they work in a smart way.
Anyway, you could just check for the result if it is infinity by
float.isInfinity(float f)
or float.isPositifinfinity(f) ...
or float.isNaN(f)
Using checking is always better when it is available than throwing and catching exceptions(they're much slower)
Hope this helped
Hi,
I tried same code snippet. I got the Exception "Attempted to Divide by zero".
Even if I check whether infinity, float.IsInfinity(), it always got the above exception.
I don't understand how come it's possible in your case?
Do you find any proper reason for that?
I tried the same program, and no exception for me. What version of .Net are you using ? (I think it don't matter, but anyway there should be something missing)
Me too, i think you should have .net 2.0 framework. There should something wrong, dividing by 0 will be thrown only when you divide integers or decimals, and not float types (float, double).
Hi soujanya, see if these examples help.
int d = 0;
int n = 5;
float v = (float) (n / d) <-- Throws exception
float v = (float)n / d <-- Does not throw exception
float v = ((float) n) / d <-- Does not throw exception
In the first case, the two numbers are still of type int when the division happens, and thus, you will get an exception. In the second and third case n is converted to a float first, and then the division happens, so you won't get an exception.
Hi Pace...
Now it's clear for me.
Earlier, I took both the numbers of Int32 type and so the exception for me.
Anyways...thanks for your clarification.