相当新,所以请原谅这个问题。我写了一个方法来取一个字符串,将它转换为一个数字,并返回该数字的因子。这很好。它调用方法并打印出令我困惑的结果。这是代码:
static void Main(string[] args)
{
Console.WriteLine("Type number to do factorial on..");
var calc = Fact(Console.ReadLine());
Console.WriteLine("The answer is " + calc);
}
private static string Fact(string numFact)
{
var number = 1;
int factorial = Convert.ToInt32(numFact);
for (int i = 1; i<= factorial; i++)
{
number *= i;
}
// Console.WriteLine(number); added to test it works
return numFact;
}
有人可以帮忙吗?你可能会从看起来猜测,如果我输入5,我会得到5。
答案 0 :(得分:3)
static void Main(string[] args)
{
Console.WriteLine("Type number to do factorial on..");
var calc = Fact(Console.ReadLine());
Console.WriteLine("The answer is " + calc);
}
private static int Fact(string numFact)
{
var number = 1;
int factorial = Convert.ToInt32(numFact);
for (int i = 1; i<= factorial; i++)
{
number *= i;
}
// Console.WriteLine(number); added to test it works
return number;
}
正如评论所述,
numFact
而不是number
。int
而不是string
以获得更好的练习,虽然这不是必需的,但它只是感觉更自然,因为它是一个数字。一旦你需要它作为一个字符串,使它成为一个字符串,这样做可能会导致以后出现问题;但是,由于这是一个非常小的项目,因此可能性很小,所以你喜欢什么。答案 1 :(得分:0)
你应该深入了解你的日志记录。您只记录了2个关键变量中的1个,因此您没有从日志中获得所需的答案。另外,将Console.Readline()
取出等式。使用硬编码。最终你可以编写测试。结帐Test Driven Development(TDD),非常适合此练习。
只修改没有TDD的日志会带来这样的结果:
static void Main(string[] args)
{
//Console.WriteLine("Type number to do factorial on..");
int sampleNumber = 5;
string sampleNumberAsString = sampleNumber.ToString();
var calc = Fact(sampleNumberAsString);
Console.WriteLine("Outside fact the answer is " + calc);
}
private static int Fact(string numFact)
{
var number = 1;
int factorial = Convert.ToInt32(numFact);
for (int i = 1; i <= factorial; i++)
{
number *= i;
}
Console.WriteLine($"Inside Fact() local variable number is {number}");//Inside Fact() local variable number is 120
Console.WriteLine($"Inside Fact() numFact parameter is is {numFact}");//Inside Fact() numFact parameter is is 5
//return numFact;//Clearly I want to return the calculated value (number) not the original value passed in (numFact)
//I'm calculating a number so let's not worry about what the caller does with the number
//Change the return type to int.
return number;
}