iwanttodie
iwanttodie

Reputation: 15

Getting Error When Converting from Decimal to Double in C#

I got an error and I don't know why. I dont find the need to convert to double or am i supposed to to that? I am really confused right now

Argument 1: cannot convert from 'decimal' to 'double'

    static void Main(string[] args)
    {


        Console.Write("speed: ");
        string speed = Console.ReadLine();
        Console.Write("Gammafaktor: ");
        string Gammafaktor = Console.ReadLine();


        {
        }
        var gamma1 = Convert.ToDecimal(Gammafaktor);
        var speed1 = Convert.ToDecimal(speed);

        if ( speed1 !=0 )
        {

            var calc = 1m / Convert.ToDecimal(Math.Sqrt(1 - speed1 * speed1));
            Console.WriteLine(calc);
        }


    }

}

}

Upvotes: 1

Views: 1141

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1064114

You are most likely seeing:

CS1503 Argument 1: cannot convert from 'decimal' to 'double'

on the line with the Math.Sqrt call, or (if you move the assignment out to a local):

CS0266 Cannot implicitly convert type 'decimal' to 'double'. An explicit conversion exists (are you missing a cast?)

Math.Sqrt takes a double, not a decimal, and the conversion from decimal to double is explicit, not implicit - meaning it isn't going to just do it automatically without you knowing about it; so:

var calc = 1m / Convert.ToDecimal(Math.Sqrt((double)(1 - speed1 * speed1)));

As a side note... that calculation looks very odd (and dangerous), unless speed1 is always between zero and one.

Upvotes: 2

Related Questions