[英]How can i write a method that contains both string and double type? should it be a void or return type method?
Basically, I want my method to contain(?) both string and double type. 基本上,我希望我的方法同时包含字符串和双精度类型的(?)。 But I don't know how to declare the method, I actually want both as a return type. 但是我不知道如何声明该方法,我实际上希望两者都作为返回类型。 It gives me an error if I declare it as a double or as a string. 如果我将其声明为双精度型或字符串型,则会给我一个错误。
This is not my original code but it is just an example and a short cut. 这不是我的原始代码,但这只是示例和捷径。
This method should print two strings and sum three doubles and print the total of the sum. 此方法应打印两个字符串并加总三个双精度数,然后打印总和。
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;
}
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);
}
After that you are taking your values like this: 之后,您将采用以下值:
Tuple<string, double> result = MethodName(a,b,n1,n2,n3);
string yourString = result.Item1;
double yourDouble = result.Item2;
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. 我认为您的问题是,即使编译器期望的是,您也不从函数返回任何内容,因此您已将函数定义为返回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 编辑:如果只想写出总和,请将返回类型更改为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. 否则,您会使编译器期望从您的函数中返回某些内容。
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. 完全按照您的问题要求-打印2个字符串,然后打印3个数字的总和。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.