在没有 Math 类库的情况下用 C# 进行除法
我编写了一个不带任何算术字符进行除法的程序,代码如下:
int num1;
int num2;
Console.WriteLine("Enter first number");
int.TryParse(Console.ReadLine(), out num1);
Console.WriteLine("Enter Second Number");
int.TryParse(Console.ReadLine(), out num2);
int sum = 0;
sum = num1;
int counter = 0;
while (sum > 0)
{
sum -= num2;
counter += 1;
}
Console.WriteLine("The division of the two numbers is " + counter);
我现在想让它显示除法的余数,例如 10 / 3 将显示 1,因为总和还剩下 1。
我该怎么做呢?我应该使用什么样的循环以及它与我的除法循环有多相似?
I have made a program that divides without any arithmetic characters, here is the code:
int num1;
int num2;
Console.WriteLine("Enter first number");
int.TryParse(Console.ReadLine(), out num1);
Console.WriteLine("Enter Second Number");
int.TryParse(Console.ReadLine(), out num2);
int sum = 0;
sum = num1;
int counter = 0;
while (sum > 0)
{
sum -= num2;
counter += 1;
}
Console.WriteLine("The division of the two numbers is " + counter);
I would now like to make it show the remainder of a division e.g. 10 / 3 will show 1 as there is 1 left from the sum.
How would I go about doing it? What kind of loop should I use and how similar is it to my division loop?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
或者如果你想让它变得非常简单,那么在循环之后:
由于你的程序有缺陷,你应该将循环更改为:
然后你在
counter
中得到除法结果,在sum< 中得到余数/代码>。
or if you want to make it really easy then after your loop:
Since your program is flawed you should change the loop to:
Then you have the division result in
counter
and the remainder insum
.然后将此行更改
为
sum
将保留其余部分,Counter
实际上将给出正确的结果。GJ
Change this line
to this
then
sum
will hold the remainder, andcounter
will actually give the correct result.GJ
余数将为
sum + num2
。The remainder will be
sum + num2
.更改
while
并在末尾添加
Change the
while
inand add at the end
我确实希望这只是一个练习,看看你是否可以在不实际除法的情况下进行除法,而不是真正尝试制定有效的除法算法!
我不想看到计算
1,000,000,000 / 1
需要多长时间无论如何,如果你必须这样做,那么余数将是
sum
加上的最终值num2
。I do hope this is just an exercise in seeing if you can divide without actually dividing and not a genuine attempt to make an efficient dividing algorithm!
I'd hate to see how long it takes to calculate
1,000,000,000 / 1
Anyway, if you must do it this way, then the remainder will be the final value of
sum
plusnum2
.