1.计算两个整数间的最大值
using System;
using System.Reflection.Metadata.Ecma335;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
int a1 = 10;
int a2 = 20;
GetMax(a1, a2);//实参
}
/// <summary>
/// 计算两个整数之间的最大值,并且返回最大值
/// </summary>
/// <param name="n1">第一个值</param>
/// <param name="n2">第二个值</param>
/// <returns>返回最大的值</returns>
public static int GetMax(int n1,int n2)//形参
{
int max = n1 > n2 ? n1 : n2;
return max;
}
// 不管是形参还是实参,都是在内存中开辟了空间的。
//
// 方法的功能一定要单一。
// 方法中最忌讳的就是出现提示用户输入的字眼。
}
}
2.读取输入的整数,定义成方法,多次调用(如果用户输入的是数字,则返回,否则提示用户重新输入)
using System;
namespace 函数方法练习
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("请输入一个整数:");
string input = Console.ReadLine();
int number = GetNumber(input);
Console.WriteLine(number);
// Console.ReadKey();
}
public static int GetNumber(string s)
{
while (true)
{
try
{
int number = Convert.ToInt32(s);
return number;
}
catch
{
Console.WriteLine("请重新输入:");
s = Console.ReadLine();
}
}
}
}
}
用户只有输入Yes或者No才会返回Yes或者No,输入其他字符需要重新输入
using System;
namespace 输入YorN
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("请输入Yes或者No");
string input = Console.ReadLine();
string result = IsYesOrNo(input);
Console.WriteLine(result);
}
/// <summary>
/// 限定用户只能输入Yes或者No 并且返回
/// </summary>
/// <param name="input">用户的输入</param>
/// <returns>返回Yes或者No</returns>
public static string IsYesOrNo(string input)
{
while (true)
{
if (input == "Yes" || input == "No")
{
return input;
}
else
{
Console.WriteLine("只能输入Yes或者No,请重新输入");
input = Console.ReadLine();
}
}
}
}
}