如何仅使用循环来划分两个用户输入,并且不允许使用任何操作?

问题描述 投票:0回答:1
Console.Write("Input Value for A: ");

int a = int.Parse(Console.ReadLine());

Console.Write("Input Value for B: ");
int b = int.Parse(Console.ReadLine());

int acc = 0;
for (int i = a; a >= b; a--)
{
    acc += b;
}

Console.Write("The quotient is {0}", acc);
Console.ReadKey(true);
c# for-loop console-application division accumulator
1个回答
0
投票

嗯,这是一个棘手的问题,因此,我立即将其解决。解决方案如下:

var quotient = 0;   
for (var acc = b; acc <= a; acc += b, quotient += 1);
Console.Write($"The quotient of {a} divided by {b} is {quotient}");

诀窍在于您仍在使用操作,但是作为循环本身的一个步骤,而不是作为循环体内的显式操作,这可能是练习的重点。

UPDATE:仅当ab具有相同的符号时,此代码才给出准确的结果。

© www.soinside.com 2019 - 2024. All rights reserved.