1. 简单函数
文档注释作用图:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace C4_程序设计
{
class 函数
{
static void Main()
{
int p;
long[] a; //长整数类型,和C++中的long long一样
long ans;
a = new long[60];
for (int i = 0; i < a.Length; i++)
{
if (i <= 2)
a[i] = 1;
else
a[i] = a[i - 1] + a[i - 2];
}
PrintFib(a);
p = Convert.ToInt32(Console.ReadLine());
ans = TheSum(a, p);
Console.WriteLine(ans);
int c, d;
string C, D;
c = 1; d = 2; C = \"1\"; D = \"2\";
Console.WriteLine(Add(c, d)); //输出结果:3
Console.WriteLine(Add(C, D)); //输出结果:12
}
static void PrintFib(long[] temp) //Pascal命名法:所有单词首字母大写,其它小写,主要用于函数和类名的定义,其实就是驼峰命名法把第一个字母改成大写
{
for (int i = 0; i < temp.Length; i++)
Console.Write(temp[i]+\" \");
Console.Write(\"\\n\");
return;
}
//三个斜杠为文档注释,主要用于对函数功能性的描述
/// <summary>
/// 求斐波那契数列的前p项和,保证p∈[0, 60]
/// </summary>
/// <param name=\"temp\">数组</param>
/// <param name=\"p\">上述p</param>
/// <returns>前缀和</returns>
static long TheSum(long[] temp, int p)
{
long ans;
ans = 0;
if (p <= -1 || p >= 61)
{
Console.WriteLine(\"输入错误\");
return -1;
}
for (int i = 0; i <= p - 1; i++)
ans += temp[i];
return ans;
}
//函数重载:和C++一样,没什么可讲的
static int Add(int a, int b)
{
return a + b;
}
static string Add(string a, string b)
{
return a + b;
}
}
}
2. ref和out参数
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace C4_程序设计
{
class 函数的高级参数
{
static void Main()
{
//求半径为p的圆的面积
double p;
p = Convert.ToDouble(Console.ReadLine());
Aera(ref p);
Console.WriteLine(p);
//求a和b的最大值和平均数
double ave;
int a, b, max, c;
//Console.WriteLine(\"max = {0}, ave = {1}\", max, ave); 错误:使用了未赋值的局部变量“max”和“ave”
a = Convert.ToInt32(Console.ReadLine());
b = Convert.ToInt32(Console.ReadLine());
c = Jud(a, b, out max, out ave);
Console.WriteLine(\"max = {0}, ave = {1}\", max, ave);
Console.WriteLine(\"c = {0}\", c);
}
static void Aera(ref double p) //ref参数:引用传递,和C++中的double &p作用一致!
{
p = p * p * 3.1415926;
}
static int Jud(int a, int b, out int max, out double ave) //out参数:若函数需要返回多个值,就要用到out参数来返回多余的值
{
if (a >= b)
max = a;
else
max = b;
ave = (1.0 * a + b) / 2;
return 1;
}
}
}
---------------------
作者:Jaihk662
来源:CSDN
原文:https://blog.csdn.net/Jaihk662/article/details/84718879
版权声明:本文为博主原创文章,转载请附上博文链接!
继续阅读与本文标签相同的文章
-
程序员的天敌,作为一名程序员新人怎样在复杂代码中找bug
2026-05-18栏目: 教程
-
东京车展丰田玩把大的 人工智能自动驾驶都有 新RAV4也将混动亮相
2026-05-18栏目: 教程
-
“北斗+”为长沙公共安全“站岗”
2026-05-18栏目: 教程
-
滴滴与清华大学成立未来出行联合研究中心
2026-05-18栏目: 教程
-
三星S10被曝屏下指纹存在安全漏洞:任何人都还可以解锁
2026-05-18栏目: 教程
