Home > Enterprise >  How do I calculate correct in C# Console App?
How do I calculate correct in C# Console App?

Time:09-22

I'm trying to calculate the follow 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. Do anyone mind explaining for me what I have to do?

CodePudding user response:

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

CodePudding user response:

using System;

public class Program
{
    public static void Main()
    {
        double equation = 25   -2 * 3.0 / 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.

CodePudding user response:

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);
    }
}

https://dotnetfiddle.net/QI2UaQ

  • Related