我正在努力理解函数在main之外是如何工作的。我只需要使用用户在main中输入的信息来计算总数,但我应该调用一个函数来计算总数。这是我到目前为止的代码,我确信它不是非常接近正确,在正确的方向上推动将是一个巨大的帮助
namespace ConsoleApplication17
{
class Program
{
static void Main(string[] args)
{
string customerName, customerState;
double numberItems, itemPrice;
Console.WriteLine("Please enter the customer name");
customerName = Console.ReadLine();
Console.WriteLine("Please enter the state in which you reside:");
customerState = Console.ReadLine();
Console.WriteLine("How many items were purchased?");
numberItems = int.Parse(Console.ReadLine());
Console.WriteLine("What was the price of said items?");
itemPrice = Convert.ToDouble(Console.ReadLine());
}
public static double ComputeTotal (double total)
{
double totalAmount;
Console.Write(total);
}
}
public static double ComputeTax (double totalAmount, string state, string fl, string nj, string ny)
{
if (state == fl)
return totalAmount*.06;
else if (state == nj)
return totalAmount*.07;
else if (state == ny)
return totalAmount*.04;
}
简而言之,我需要使用ComputeTotal函数来乘以numberItems和itemPrice
答案 0 :(得分:3)
一个函数基本上从你那里获取一些数据并返回(其他一些?)数据给你。 在您的情况下,您想要为函数提供2个数据 - 数量和价格,并且您希望它返回总价格。
public static double ComputeTotal(double qty, double price)
{
return qty* price;
}
此函数ComputeTotal接受2个double类型的变量。 他们是数量和价格。 然后,该函数将这两个变量相乘,并将结果返回给调用者。
在您的main方法中,这是您使用(调用)函数的方式。
static void Main(string[] args)
{
// rest of your code here
var total = ComputeTotal(numberItems, itemPrice);
Console.WriteLine(total);
}
这里我创建了一个名为total的新变量,我将ComputeTotal函数的返回值赋给此变量。
ComputeTotal函数需要2个参数,并且我传递了您在代码中创建的2个变量。为简洁起见,我没有输入任何原始代码,您的代码应位于我的评论位置" //其余代码在此处" 。
答案 1 :(得分:1)
your method/function could be like this
public static double ComputeTotal (double itemPrice, int quantity)
{
return itemPrice * quantity
}
在您的主要方法中,您可以这样做
static void Main(string[] args)
{
double total_price=0.0;
total_price = ComputeTotal ( itemPrice, numberItems)
Console.WriteLine("totl price : {0}",total_price);
}
答案 2 :(得分:1)
了解功能如何运作
我正在大量提炼,但这个定义的函数实际上是method
,它返回一个值。在C#中,functions
和methods
之间没有区别,因为它们是相同的,不同之处在于某些东西是返回数据还是在类实例的引用实例上操作。
真正的区别是在调用机制中是否有一个实例化(在类上调用new
);他们实例化了一个班级。对于此作业,您的教师不希望您实例化课程。
因此,您将调用 function(s),这些static
方法可由任何人调用,无需实例化任何类。
考虑到这一点,您的老师希望您学习function
类型的通话,以便他/她希望您创建一个static
方法,可以调用类Program
按Main
,因为它也是静态的。
因此,创建将返回值的函数类型的静态方法;因此它会模仿其他语言中的functions
。
在主要之外。
现在Main
可以有静态方法,但是其他类也可以从Main
的静态方法中调用。
这样的其他类看起来像这样......并且通过完全限定{ClassName}
。{Static Method Name}
等位置来称为 。
class Program {
static void Main(...)
{
Console.WriteLine( TheOtherClass.AFunction() );
}
}
public class TheOtherClass
{
public static string AFunction()
{
return "A String From this Function. :-) ";
}
}
请注意,如果TheOtherClass位于不同的命名空间中,请访问{Namespace}
。{ClassName}
。{Static Method Name}
。但是,您应该确保其他类与Namespace
的当前示例中的ConsoleApplication17
相同。