方法/函數(shù)8(綜合應用)
static int Getnumber(string s)//第一個自定義函數(shù),判斷輸入的字符是否合規(guī)
{
? ? ? ? while (true)
? ? ? ? {
? ? ? ?? ? ? ? try
? ? ? ? ? ? ?? {
? ? ? ? ? ? ? ? ? ? ? ?int number = Convert.ToInt32(s);//如果輸入的是字母,那么就轉變不了
? ? ? ? ? ? ? ? ? ? ? ?return number;
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? catch?
? ? ? ? ? ? ? ? {?
? ? ? ? ? ? ? ? ? ? ???Console.WriteLine("輸入有誤??!請重新輸入") ;//如果輸入的是字母,那么就? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?//會執(zhí)行這個
? ? ? ? ? ? ? ? ? ? ? ?s = Console.ReadLine();
? ? ? ? ? ? ? ? ?}
? ? ? ? }
}
static?void Judgenumber(ref int n1, ref int n2)//第二個自定義函數(shù),判斷輸入的第二個數(shù)是不? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?//是比第一個數(shù)大
{
? ? ? ? ?if (n1 < n2)
? ? ? ? ?{
? ? ? ? ? ? ? ? return;
? ? ? ? ? }
? ? ? ? ? else?
? ? ? ? ? {
? ? ? ? ? Console.WriteLine("第一個數(shù)字不能大于或者等于第二個數(shù)字,請重新輸入??!");
? ? ? ? ? string s1 = Console.ReadLine();
? ? ? ? ? n1 = Getnumber(s1);
? ? ? ? ? Console.WriteLine("請重新輸入第二個數(shù)字");
? ? ? ? ? string s2 = Console.ReadLine();
? ? ? ? ? n2 = Getnumber(s2);
? ? ? ? ? }
}
static int Getsum(int num1,int num2)//第三個自定義函數(shù),計算兩個數(shù)之間所有數(shù)的和
{
? ? ? ? ? int sum = 0;
? ? ? ? ? for (int i = num1; i < num2 + 1; i++)
? ? ? ? ? { sum += i ;?}
? ? ? ? ? return sum;
}
static void Main(string[] args)
{
? ? ? ? ?Console.WriteLine("請輸入第一個數(shù)");
? ? ? ? ?string str = Console.ReadLine();
? ? ? ? ?int str1 = Getnumber(str);//引用第一個函數(shù)
? ? ? ? ?Console.WriteLine("請輸入第二個數(shù)");
? ? ? ? ?string stra = Console.ReadLine();
? ? ? ? ?int str2 = Getnumber(stra);//引用第二個函數(shù)
? ? ? ? ?Judgenumber(ref str1,ref str2);//判斷第二個數(shù)是否大于第一個數(shù)
? ? ? ? ?int sum = Getsum(str1, str2);//計算兩個數(shù)之間的和
? ? ? ? ?Console.WriteLine("這兩個數(shù)累加的和是:"+sum);
}??