我正在通过一些编码练习来教自己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
答案 0 :(得分:2)
您没有初始化字段。另外,由于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
答案 1 :(得分:1)
构造函数有两个不同的名为seconds
的变量:类成员和参数。您需要这样做:
public SpaceAge(long seconds)
{
this.seconds = seconds;
Console.WriteLine("Space Age in Seconds:" + seconds);
}
此外,OnEarth()
中的算术完全发生在整数空间中,这意味着结果的任何小数部分都会被截断。您需要确保除法运算的至少一侧是浮点类型:
public class SpaceAge
{
public long seconds;
public SpaceAge(long seconds)
{
this.seconds = seconds;
Console.WriteLine("Space Age in Seconds:" + seconds);
}
public double OnEarth()
{
//the "D" at the end of the number means it is a double, not an int.
return seconds / 31557600D;
}
public double OnMercury()
{
return seconds * 0.2408467D;
}
}