0

I'm trying to calculate the area of a sector but when I divide angleParse by 360 and times it by radiusParse, I will sometimes receive a output of 0.

What happens and where do I need to fix it? (Sorry, if this is a weird question but I started learning C# yesterday, also I just started using StackOverflow today)

Frostbyte

static void AoaSc()
{
    Console.WriteLine("Enter the radius of the circle in centimetres.");
    string radius = Console.ReadLine();
    int radiusParse;
    Int32.TryParse(radius, out radiusParse);
    Console.WriteLine("Enter the angle of the sector.");
    string sectorAngle = Console.ReadLine();
    int angleParse;
    Int32.TryParse(sectorAngle, out angleParse);
    double area = radiusParse * angleParse / 360;
    Console.WriteLine("The area of the sector is: " + area + "cm²");
    Console.ReadLine();
}
Will Vousden
  • 32,488
  • 9
  • 84
  • 95
Frostbyte
  • 3
  • 3

2 Answers2

4

You've encountered integer division. If a and b are int, then a / b is also an int, where the non-integer part has been truncated (i.e. everything following the decimal point has been cut off).

If you want the "true" result, one or more of the operands in your division needs to be a floating point. Either of the following will work:

radiusParse * (double)angleParse / 360;
radiusParse * angleParse / 360.0;

Note that it's not sufficient to cast radiusParse to double, because the / operator has higher precedence than * (so the integer division happens first).

Finally, also note that decimal in .NET is its own type, and is distinct from float and double.

Will Vousden
  • 32,488
  • 9
  • 84
  • 95
2

I think if you divide it by 360.0 it will work.

Alternatively declare a variable of type decimal and set this to 360.

private decimal degreesInCirle = 360;

// Other code removed...

double area = radiusParse * angleParse / degreesInCirle;
amcdermott
  • 1,565
  • 15
  • 23