用C#的方法输入一个整数,输出它的约数个数
发布网友
发布时间:2024-04-01 21:06
我来回答
共2个回答
热心网友
时间:2024-04-24 15:07
static void Main(string[] args)
{
String str = "";
int digit = 1;
#region "接收用户输入"
Console.WriteLine("请输入一个整数,以回车结束:");
while (true)
{
try
{
str = Console.ReadLine();
digit = Convert.ToInt16(str);
break;
}
catch (System.Exception)
{
Console.WriteLine(String.Format("输入的值'{0}'不正确,请重新输入:", str));
}
}
#endregion
List<int> submultiples = new List<int>();
for(int i=1; i<=digit; i++)
{
if (digit%i == 0)
{
submultiples.Add(i);
}
}
Console.WriteLine(String.Format("{0}的约数有{1}个:",
digit, submultiples.Count));
Console.WriteLine("按任意键退出程序。");
Console.ReadLine();
}
热心网友
时间:2024-04-24 15:04
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NumberOperation
{
class NumberOperation
{
/// <summary>
/// 返回指定整数的约数集合
/// </summary>
/// <param name="num"></param>
/// <returns></returns>
public static List<int> Divisors(int num)
{
List<int> divisors = new List<int>();
for (int i = 1; i <= num; i++)
{
if (0 == num % i)
{
divisors.Add(i);
}
}
return divisors;
}
/// <summary>
/// 计算指定整数约数的和
/// </summary>
/// <param name="num"></param>
/// <returns></returns>
public static int SumDivisors(int num)
{
int sum = 0;
foreach (int i in Divisors(num))
{
sum += i;
}
return sum;
}
}
}