2

I'm trying to calculate the following equation in a C# console application:

double equation = 25 + -2 * 3 / 14; 
Console.WriteLine(equation);

And the outcome is 25.

Which is not the accurate answer to the equation. Does anyone mind explaining to me what I have to do?

Alisettar Huseynli
  • 944
  • 1
  • 11
  • 24
  • 2
    Does this answer your question? [Why does integer division in C# return an integer and not a float?](https://stackoverflow.com/questions/10851273/why-does-integer-division-in-c-sharp-return-an-integer-and-not-a-float) – Franz Gleichmann Sep 22 '21 at 12:56

3 Answers3

4

Try this

using System;

public class Program
{
    public static void Main()
    {
        double equation = 25 + -2 * 3 / 14d;
        Console.WriteLine(equation);
    }
}

The issue is that you are doing your operations with integers (whole numbers) so the result will be an integer that you cast as a double. What you need to do is specify that you division operation is done on a float or double so the answer to the division part will not be a whole number. You can also do this with 14.0 or 14f but it is better to stick to the same data type to avoid conversion issues later on.

You can test your code here: https://dotnetfiddle.net/Tlws6e

eglease
  • 2,445
  • 11
  • 18
  • 28
2
using System;

public class Program
{
    public static void Main()
    {
        double equation = 25 + -2 * 3 / 14.0;
        Console.WriteLine(equation);
    }
}

This should help. When you want results in doubles and floats, and you are using literals, add a .0. This results in 24.5714285714286.

Musaab
  • 1,574
  • 3
  • 18
  • 37
1

For more precision you can use decimal type

using System;

public class Program
{
    public static void Main()
    {
        decimal equation = 25m + -2m * 3m / 14m;
        Console.WriteLine(equation);
    }
}

Demo: https://dotnetfiddle.net/QI2UaQ

Exact result: https://www.wolframalpha.com/input/?i=25+%2B+-2+*+3+%2F+14

Tohm
  • 305
  • 1
  • 5