如何在 C# 中使用 return 语句?
return 语句用于返回值。当程序调用函数时,程序控制权将转移到被调用的函数。被调用的函数执行一个已定义的任务,当其 return 语句被执行或当其函数结束的闭合花括号被触及时,它将程序控制权返回到主程序。
以下是有关如何在 C# 中使用 return 语句的示例。在此,我们查找一个数字的阶乘并使用 return 语句返回结果。
while (n != 1) {
res = res * n;
n = n - 1;
}
return res;以下是完整示例。
示例
using System;
namespace Demo {
class Factorial {
public int display(int n) {
int res = 1;
while (n != 1) {
res = res * n;
n = n - 1;
}
return res;
}
static void Main(string[] args) {
int value = 5;
int ret;
Factorial fact = new Factorial();
ret = fact.display(value);
Console.WriteLine("Value is : {0}", ret );
Console.ReadLine();
}
}
}输出
Value is : 120
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP