首页 > 解决方案 > 类方法不使用类变量

问题描述

我正在通过几个编码练习来自学 C#,现在已经卡住了几天,试图计算其他星球上的不同时间段,是时候挖掘并寻求帮助了。我至少已经摆脱了错误并且它开始返回一些东西,但现在对于我的生活,我无法弄清楚为什么seconds不能以稳定的方式存储然后调用方法。它只是返回零。请看下面的代码。

    public class SpaceAge
    {
        public long seconds;

        public SpaceAge(long seconds)
        {
            Console.WriteLine("Space Age in Seconds:" + seconds); 
        }

        public double OnEarth()
        {
            double result = seconds / 31557600;
            return result;
        }
        public double OnMercury()
        {
            double result = seconds * 0.2408467;
            return result;
        }
    }  

    class Program
    {
        public static void Main()
        {
             Console.WriteLine("**Main Function Executing**");
             var age = new SpaceAge(10000000000);
             Console.WriteLine("Earth years:" + age.OnEarth());
             Console.WriteLine("Mercury years:" + age.OnMercury());       
        }
    }

它返回:

BBs-iMac:space-age bb$ dotnet run
**Main function executing**
Space Age in Seconds:10000000000
Earth years:0
Mercury years:0

标签: c#

解决方案


你没有初始化你的领域。另外,因为你应该在除数上 seconds使用long后缀。D

using System;

public class SpaceAge
{
    public long seconds;
    public SpaceAge(long seconds)
    {
        this.seconds = seconds; // missing
        Console.WriteLine("Space Age in Seconds:" + seconds);
    }

    public double OnEarth()
    {
        double result = seconds / 31557600D; // add an 'D'
        return result;
    }

    public double OnMercury()
    {
        double result = seconds * 0.2408467D; // add an 'D'
        return result;
    }
}

public class Program
{
    public static void Main()
    {
        Console.WriteLine("**Main Function Executing**");
        var age = new SpaceAge(10000000000);
        Console.WriteLine("Earth years:" + age.OnEarth());
        Console.WriteLine("Mercury years:" + age.OnMercury());
    }
}

输出:

没有“D”后缀

**Main Function Executing**
Space Age in Seconds:10000000000
Earth years:316
Mercury years:2408467000

带“D”后缀:

**Main Function Executing**
Space Age in Seconds:10000000000
Earth years:316.88087814029
Mercury years:2408466935.15778

推荐阅读