如何编写包含字符串和双精度类型的方法?它应该是无效还是返回类型的方法?

时间:2016-12-09 12:35:35

标签: c# string methods double void

基本上,我希望我的方法包含(?)字符串和双精度类型。 但我不知道如何声明方法,我实际上想要两者作为返回类型。 如果我将其声明为double或字符串,则会给出错误。

这不是我的原始代码,但它只是一个例子和捷径。

此方法应打印两个字符串并将三个双打相加并打印总和。

public static double MethodName ( string A, string B, double n1, double n2, double n3)

{
   double sum;    
   Console.Write(A);    
   Console.Write(B);    
   sum= n1+n2+n3;    
}

3 个答案:

答案 0 :(得分:2)

public static Tuple<string, double> MethodName ( string A, string B, double n1, double n2, double n3)
{
   double sum;

   Console.Write(A);

   Console.Write(B);

   sum= n1+n2+n3;

   return new Tuple<string, double>("yourString", sum);
}

您可以使用Tuple

之后,您将采用以下值:

Tuple<string, double> result = MethodName(a,b,n1,n2,n3);
string yourString = result.Item1;
double yourDouble = result.Item2;

答案 1 :(得分:0)

I think your problem is that you're not returning anything from the function even tho compiler is expecting so as you've defined your function as returning double. In case you want to your last line should be something like

...
return sum;
}

or if you want it one line shorter then

...
return n1+n2+n3;
}

Class declaration is fine if you only want to return double value.

EDIT: In case you want only to write out the sum, change return type to void

public static void MethodName ( string A, string B, double n1, double n2, double n3)

Otherwise you're making compiler expect something to be returned from your function.

答案 2 :(得分:0)

public void MethodName (string A, string B, double n1, double n2, double n3)
{
    double sum = n1 + n2 + n3;

    Console.WriteLine(A);
    Console.WriteLine(B);
    Console.WriteLine(sum.ToString());
}

Does exactly what your question asks - Prints the 2 strings, then the sum of the 3 numbers.