C# 用两个类计算圆的面积

C# 用两个类计算圆的面积,c#,C#,这是我第一次使用这个论坛!我是一名大学二年级学生,刚刚开始用C编写代码,就像我们去年用java编写代码一样 其中一个实验练习是编写一个小程序,弹出一个终端窗口,要求输入一个数字十进制数,这是程序通过调用另一个类中的方法计算面积的半径 我在VisualStudio2008中编写了代码,使用相同的名称空间,它构建并运行,但不工作? 以下是不同类别的代码,如有任何帮助/建议,将不胜感激 守则: using System; using System.Collections.Generic; using

这是我第一次使用这个论坛!我是一名大学二年级学生,刚刚开始用C编写代码,就像我们去年用java编写代码一样

其中一个实验练习是编写一个小程序,弹出一个终端窗口,要求输入一个数字十进制数,这是程序通过调用另一个类中的方法计算面积的半径

我在VisualStudio2008中编写了代码,使用相同的名称空间,它构建并运行,但不工作? 以下是不同类别的代码,如有任何帮助/建议,将不胜感激

守则:

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

namespace Program4
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter The Radius:");//Text to be displayed in the console
            Console.ReadLine();//Read the line and store information in temp directory
            Pie one = new Pie();//Calls the method from the class in the same namespace
            Console.ReadKey();//Reads and displays the next key pressed in the console   
            Environment.Exit(0);//Exit the Enviromet        
        }
    }
}


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

namespace Program4
{
    class Pie
    {    
        public void Pin ()
        {
            int r;//defining the value that is going to be entered as an integer 
            double result;//declaring the result string as a double
            r = (int)Convert.ToDouble(Console.ReadLine());
            result=(3.14*r*r);//the calculation to work out pie
            Console.WriteLine("The Radius of the circle is " + (result));//the writeline statement    
         }
    }
}

将静态添加到类饼图和公共void Pin。它会起作用的

    static class Pie
    {

          public static void Pin ()
          {
            int r;//defining the value that is going to be entered as an integer 
            double result;//declaring the result string as a double
            r = (int)Convert.ToDouble(Console.ReadLine());
            result=(3.14*r*r);//the calculation to work out pie
            Console.WriteLine("The Radius of the circle is " + (result));//the writeline statement    
         }
    }
或者,如果您愿意,您可以实例化该类,然后像那样调用该方法

Pie pie=new Pie();
pie.Pin();

您可以尝试运行以下代码:

Pie one = new Pie();
one.Pin();
此外: 这一行:

Console.ReadLine();//Read the line and store information in temp directory
这一评论是非常错误的。它应该是//读这行,然后把结果扔掉

这是:intConvert.ToDoubleConsole.ReadLine;
可以替换为:int.ParseConsole.ReadLine

您需要实际调用Pin方法。你打了两次电话给ReadLine,如果你打电话给Pin,你只需要一次。你还需要看看你的数学。如果result=3.14*r*r,则result不是.Pin中WriteLine所述的半径…感谢您的评论,我将重新访问代码将它们更改为static将不起作用,除非您调用您未提及的Pie.Pin。从这个问题可以清楚地看出,用户误解了类实例和方法调用是如何工作的。所以这就是一个好的答案应该关注的——教OP如何做事correctly@musefan谢谢你的回答。一旦我开始休息,我将编辑并解释差异