简体   繁体   中英

C# Math.Sqrt() not working

So I am still rather new to C# programming, so I'm sure I'm making a very simple mistake here. I am using visual studio to make a console application and in this application, I am trying to find the square root of a number. I have the .NET framework.
Here is the top of my program:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Linear
{
    public static class Math
    {
        static void Main()
        {
          // program in here
        }
     }
}

In the program, I have a line that goes like this:

double distanceA = Math.Sqrt(totalA);

So when I build the program with VS, it tells me that 'Linear.Math' does not contain a definition for 'Sqrt'. Why does it say this? How can I give it a definition for 'Sqrt'?

Because you named your class Math , Visual Studio and the compiler do not know if you are referring to your own class ( Linear.Math ), or the .NET Math class ( System.Math ).

You can specify that you would like to use the .NET Math class by instead by fully qualifying the name.:

double distanceA = System.Math.Sqrt(totalA);

This specifies you would like to use System.Math . You can use this throughout the entire file by adding the following after your using directives:

using Math = System.Math;

This is called the using alias directive , which will tell the compiler that Math refers to System.Math .

Note that it's usually not advised to use conflicting names when creating your own classes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM