首先,设置两个数字。
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("数字不能小于除数!"); 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("数字不能小于除数!"); 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