C# 程式接收兩個整數並返回餘數


首先,設定兩個數字。

int one = 250;
int two = 200;

現在將這些數字傳遞給以下函式。

public int RemainderFunc(int val1, int val2) {
   if (val2 == 0)
   throw new Exception("Second number cannot be zero! Cannot divide by zero!");
   if (val1 < val2)
   throw new Exception("Number cannot be less than the divisor!");
   else
   return (val1 % val2);
}

上面我們檢查了兩個條件,即

  • 如果第二個數字為零,則會發生異常。
  • 如果第一個數字小於第二個數字,則會發生異常。

要返回兩個數字的餘數,以下是完整程式碼。

示例

 現場演示

using System;
namespace Program {
   class Demo {
      public int RemainderFunc(int val1, int val2) {
         if (val2 == 0)
         throw new Exception("Second number cannot be zero! Cannot divide by zero!");
         if (val1 < val2)
         throw new Exception("Number cannot be less than the divisor!");
         else
         return (val1 % val2);
      }
      static void Main(string[] args) {
         int one = 250;
         int two = 200;
         int remainder;
         Console.WriteLine("Number One: "+one);
         Console.WriteLine("Number Two: "+two);
         Demo d = new Demo();
         remainder = d.RemainderFunc(one, two);
         Console.WriteLine("Remainder: {0}", remainder );
         Console.ReadLine();
      }
   }
}

輸出

Number One: 250
Number Two: 200
Remainder: 50

更新於:23-Jun-2020

602 瀏覽

啟動你的 職業

完成課程即可獲得認證

開始學習
廣告
© . All rights reserved.