我剛剛開始學習C#。並碰到一個問題: 當我在主要方法中使用Console.WriteLine時,它工作得很好。但是,當我嘗試將代碼分解爲方法時,WriteLine不會返回任何內容。 (我使用Visual Studio來構建和編譯項目)。C#Console.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 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
您不會從任何地方撥打電話。您需要從Main方法調用Calculate。 – NineBerry
Basic 101 C#編程:一個正在運行的代碼,當到達方法的右花括號時,返回給調用該方法的任何人。它不會繼續執行下一個方法,然後執行下一個方法。您應該以某種方式驅動您的代碼 – Steve
您需要真正瞭解更多關於局部變量以及如何調用方法的信息,當您運行控制檯時執行的代碼只是包含在主要代碼中的任何主程序中沒有調用的代碼是無用的 – hdrdiab