c# - 类方法不使用类变量
问题描述
我正在通过几个编码练习来自学 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
解决方案
你没有初始化你的领域。另外,因为你应该在除数上 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
推荐阅读
- java - 如何根据来自 JPanel 的操作事件关闭 Java JFrame
- python - 基于间隔的 Numpy / Pandas 切片
- xcode - 如何在 SwiftUI 中显示显示数组的文本
- vb.net - VB.NET + LINQ:将查询不同表中两列的结果保存在单个类属性中
- java - NotFoundException 被抛出以尝试获取现有类
- java - “POST”方法使用放心抛出 500 代码
- python - 从多个文件构建数据框,其中每个文件包含列数据
- database - 原因:SQL(查询)错误或缺少数据库。- 在颤振/飞镖中
- reactjs - 即使我没有在 react 应用程序的 req.body 中附加 _csrf,Express csurf 中间件也总是被接受,但 api 按预期在邮递员中工作
- javascript - 从本地存储中获取数据