Computer >> Máy Tính >  >> Lập trình >> C#

Chương trình C # chấp nhận hai số nguyên và trả về phần còn lại

Đầu tiên, hãy đặt hai số.

int one = 250;
int two = 200;

Bây giờ, hãy chuyển những số đó vào hàm sau.

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);
}

Ở trên, chúng tôi đã kiểm tra hai điều kiện, tức là

  • Nếu số thứ hai bằng 0, một ngoại lệ sẽ xảy ra.
  • Nếu số đầu tiên nhỏ hơn số thứ hai, một ngoại lệ sẽ xảy ra.

Để trả về phần còn lại của hai số, sau đây là mã hoàn chỉnh.

Ví dụ

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();
      }
   }
}

Đầu ra

Number One: 250
Number Two: 200
Remainder: 50