我刚开始研究C#。并遇到了一个问题: 当我在 Main 方法中使用Console.WriteLine时,它可以正常工作。但是,当我尝试将代码分解为方法时,WriteLine不会返回任何内容。 (我使用Visual Studio来构建和编译项目)。
任务是找到一个人在按月资本化存款时可以获得的最终金额。我有点怀疑我只是搞砸了一些微不足道的事情,但仍然会欣赏一个解释:)谢谢
没有方法的代码:
using System;
class Program
{
static void Main()
{
//User input
Console.WriteLine("Enter the initial amount, percentage, and deposit time (months)");
string userInput = Console.ReadLine();
//Separating the input string into substrings
string[] separated = userInput.Split(' ');
//Getting the main variables
double sum1 = double.Parse(separated[0]);
double oneMonthPercentage = double.Parse(separated[1]) / 1200; //find a montly amount in percent = amount / 12 month / 100
double months = double.Parse(separated[2]);
double initialSum = sum1;
//Calculation of the final ammount
for (int i = 1; i <= months; i++)
{
sum1 += sum1 * oneMonthPercentage;
}
//Output
Console.WriteLine("Ammount: " + initialSum);
Console.WriteLine("Percentage: " + oneMonthPercentage * 1200 + "%");
Console.WriteLine("Time: " + months);
Console.WriteLine("Final amount: " + Math.Round(sum1, 2));
}
}
输出 - no_methods
带方法的代码(WriteLine不起作用):
using System;
class Program
{
static void Main()
{
//User input
Console.WriteLine("Enter the initial amount, percentage, and deposit time (months)");
string userInput = Console.ReadLine();
}
//Separating string into substrings
public static string[] SeparateString(string userInput)
{
string[] separated = userInput.Split(' ');
return separated;
}
//calculating the final amount at the end of deposit time
public static double Calculate(string userInput)
{
// defining main variables for calculation
double sum1 = double.Parse(SeparateString(userInput)[0]);
double oneMonthPercentage = double.Parse(SeparateString(userInput)[1]) / 1200;
double months = double.Parse(SeparateString(userInput)[2]);
double initialSum = sum1;
//calculation as to the formula
for (int i = 1; i <= months; i++)
{
sum1 += sum1 * oneMonthPercentage;
}
//Output
Console.WriteLine("Ammount: " + initialSum);
Console.WriteLine("Percentage: " + oneMonthPercentage * 1200 + "%");
Console.WriteLine("Time: " + months);
Console.WriteLine("Final amount: " + Math.Round(sum1, 2));
return sum1;
}
}
输出 - with_methods
答案 0 :(得分:5)
您需要调用这些方法才能使它们正常工作。现在你只调用初始的WriteLine和ReadLine
答案 1 :(得分:3)
您不会调用任何方法。你应该调用Calculate()
方法:
static void Main()
{
//User input
Console.WriteLine("Enter the initial amount, percentage, and deposit time (months)");
string userInput = Console.ReadLine();
var result = Calculate(userInput); // call here
}