【发布时间】:2017-02-20 13:35:10
【问题描述】:
我正在尝试完成此页面底部的任务,但它给了我一个无限循环,如果我添加教程的建议将数字除以因子并将其分配给它不会打印所有的数字数字的因素,例如,如果我输入 20,它只会打印 4、5(当我添加之前在 Console.Write(candidateFactor) 下添加的 number = number/candidateFactor 时;
我想知道我做错了什么,任何帮助将不胜感激。
https://www.microsoft.com/net/tutorials/csharp/getting-started/looping-logical-expression
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Loops
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter a number:");
int number = int.Parse(Console.ReadLine());
Console.Write("Factors: ");
while (number > 1) // convert this to while
{
int candidateFactor = 2;
while (candidateFactor <= number) // convert this to while
{
candidateFactor++;
if (number % candidateFactor == 0) // found a factor
{
Console.Write(candidateFactor);
if (number > 1)
{
Console.WriteLine(", ");
}
// divide number by the factor you found and assign this back to number
// print a comma if number is still greater than 1
}
// don't forget to increment factor!
}
}
Console.ReadLine();
}
}
}
【问题讨论】:
-
您永远不会重新分配
number,因此它始终具有相同的值。 -
检查这一行.... // 不要忘记增加因子!
-
我把candidateFactor++ 增加,如果我分配number = number/candidateFactor 它不会返回所有的因素。
-
您的问题已经得到了很好的答案,但我会注意,candidateFactor 应该从 1 开始。否则,您不会将 1 显示为数字的有效因子(它是)。
标签: c# loops while-loop factors