-5
using System;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            int a, b;
             Console.Write("Enter two values :- ");
             a = Convert.ToInt32(Console.ReadLine());
             b = Convert.ToInt32(Console.ReadLine());
             float c =(a / b);
            Console.WriteLine("\nAnswer is :- {0}",c);            
            Console.ReadLine();
        }
    }
}
DGibbs
  • 14,316
  • 7
  • 44
  • 83
  • 2
    This is the classic integer divison question. One of your operands has to be a float for the division to work as you expect. – BradleyDotNET Jul 25 '14 at 16:20
  • Use `Convert.ToDouble(..)` for `a` and `b`. – afaolek Jul 25 '14 at 16:20
  • possible duplicate of [Why integer division in c# returns an integer but not a float?](http://stackoverflow.com/questions/10851273/why-integer-division-in-c-sharp-returns-an-integer-but-not-a-float) – BradleyDotNET Jul 25 '14 at 16:20

2 Answers2

2

The expression (a / b) (where both a and b are ints) will result in an int, which is then converted to a float when assigned to c.

To get a float, you should make either a or b a float, or cast one to a float:

float c = (a / (float)b); // Int divided by float is a float

Or, just make a and b floats in the first place:

float a, b;
Mike Christensen
  • 88,082
  • 50
  • 208
  • 326
0

Because a and b are both integers, the result of division is also an integer. After the division, it is cast to a float, but it is too late by then.

For this to work, at least one of the operands must be a float. Try this:

float c = ((float) a) / b;
metacubed
  • 7,031
  • 6
  • 36
  • 65