我正在编写质因数分解代码,并且尝试在用户输入的数字的每个显示的质因数之间打印“x”。但是,我似乎不知道如何做到这一点,以便在最后显示的素因数之后不会出现额外的“x”。
我尝试过在 print 语句中的“x”之后连接 mod,并且尝试考虑使用 If 语句 for (startInt % mod == 0),但我不太确定 else 语句是什么为了那个原因。
System.out.println("Enter an integer to be factored:");
int startInt = userInput.nextInt();
if(startInt % 2 == 0 || startInt % 3 == 0 || startInt % 5 == 0 || startInt % 7 == 0 || startInt % 11 == 0 || startInt % 13 == 0)
{
for(int mod = 2; mod <= startInt; mod++)
{
while(startInt%mod == 0)
{
startInt /= mod;
System.out.print(mod+" x ");
}
}
}
else
{
System.out.println(startInt+" = "+startInt);
System.out.println(startInt+" is a prime number.");
}
我预计 784784 的输出为 2 x 2 x 2 x 2 x 7 x 7 x 7 x 11 x 13,但实际输出为 2 x 2 x 2 x 2 x 7 x 7 x 7 x 11 x 13 x。
检查这个示例(我将其改编为Javascript,但固定行是两种语言的示例):
const System = {
out: {
println: console.log
}
};
System.out.println("Enter an integer to be factored:");
let startInt = 784784;
const expectedResult = '2 x 2 x 2 x 2 x 7 x 7 x 7 x 11 x 13'
if(startInt % 2 == 0 || startInt % 3 == 0 || startInt % 5 == 0 || startInt % 7 == 0 || startInt % 11 == 0 || startInt % 13 == 0) {
let result = '';
for(let mod = 2; mod <= startInt; mod++) {
while (startInt%mod === 0) {
startInt /= mod;
// Fix this line
result += mod + (mod < startInt ? ' x ' : '');
}
}
System.out.println(result);
if (result !== expectedResult) {
System.out.println('Fail');
} else {
System.out.println('Everything is Ok');
}
} else {
System.out.println(startInt+" = "+startInt);
System.out.println(startInt+" is a prime number.");
}
您必须避免在最后一个循环中添加“x”:
结果 += mod + (mod
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)