![](/img/trans.png)
[英]C# console application - commission calculator - how to use method within method
[英]C# console application - commission calculator - how to pass variables into Main()
我不知道如何將總計,銷售和通訊傳遞到Main()中。
有人知道如何將這些變量放入Main並在其中顯示(輸出)它們的名稱嗎?
現在,我可以在calcComm中輸出變量。
提前致謝
菲利浦
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication38
{
class Program
{
public static void getsales()
{
string inputsales;
double total = 0;
double sale = 0;
for (int salecount = 1; salecount <= 3; ++salecount)
{
Console.WriteLine("Enter sale: ");
inputsales = Console.ReadLine();
sale = Convert.ToDouble(inputsales);
total = total + sale;
}
calcComm(total);
}
public static void calcComm(double total)
{
double comm = 0;
comm = total * 0.2;
Console.WriteLine(comm);
}
public static void Main ()
{
Console.WriteLine(" Sunshine Hot Tubs \n Sales Commissions Report\n");
char Letter;
const string name1 = "Andreas";
const string name2 = "Brittany";
const string name3 = "Eric";
string inputLetter;
string name;
Console.WriteLine("Please enter intial or type 'z' to quit");
inputLetter = Console.ReadLine();
Letter = Convert.ToChar(inputLetter);
while (Letter != 'z')
{
if (Letter == 'a')
{
name = name1;
getsales();
}
else if (Letter == 'b')
{
name = name2;
getsales();
}
else if (Letter == 'e')
{
name = name3;
getsales();
}
else
{
Console.WriteLine("Invalid entry try again");
}
Console.WriteLine("Please enter intial or type z to quit");
inputLetter = Console.ReadLine();
Letter = Convert.ToChar(inputLetter);
}
}
}
}
這給出了與命令行參數相對應的字符串數組。
Main(string [] args)
順便說一句,在處理貨幣單位時,最好使用十進制而不是雙精度。
您應該使用對象,然后可以將其公開。
class Sales
{
public double total;
public double sale;
public double comm;
...
public void CalcComm()
{
...
}
}
然后,您可以像這樣引用它們:
Sales.total, Sales.sale
或者您可以將它們設置為全局,但是通常不建議這樣做。
查看C#中的return
關鍵字; 讓您的函數將相關數據返回給main
並加以利用。
考慮此示例,了解如何添加命令行參數。 如果需要以編程方式添加它們,請考慮編寫包裝程序並在其中啟動Process。
using System;
class Program
{
static void Main(string[] args)
{
if (args == null)
{
Console.WriteLine("args is null"); // Check for null array
}
else
{
Console.Write("args length is ");
Console.WriteLine(args.Length); // Write array length
for (int i = 0; i < args.Length; i++) // Loop through array
{
string argument = args[i];
Console.Write("args index ");
Console.Write(i); // Write index
Console.Write(" is [");
Console.Write(argument); // Write string
Console.WriteLine("]");
}
}
Console.ReadLine();
}
}
或者,您可以建立一個包含這三個變量的數據傳輸對象實例化它,然后將其返回到您的主函數。
您還可以使用作為引用而不是按值傳遞的變量,並使用更新的參考值。 了解有關c#的按值傳遞類型和引用類型以及ref
關鍵字的信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.