How do I calculate correct in C# Console App?

Viewed 81

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?

3 Answers

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

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.

Related