我的任务是:编写一个程序,读取两个正整数并打印它们之间存在多少个数字,使得除以5的提示为0(含)。示例:p(17,25)= 2.
Console.Write("Enter min: ");
int min = int.Parse(Console.ReadLine());
Console.Write("Enter max: ");
int max = int.Parse(Console.ReadLine());
Console.WriteLine("The numbers devidable by 5 without remainder from {0} to {1} are: ",min,max);
for (int i = min; i <= max; i++)
{
if (i % 5 == 0)
{
Console.WriteLine(i);
}
}
这将打印出范围内可分为5的数字......如何计算有多少数字并在控制台中打印计数?
答案 0 :(得分:8)
对于正面参数,您可以在O(1)中执行:
int DivisibleBy5From0To(int n)
{
return (n / 5) + 1;
}
int DivisibleBy5FromTo(int lo, int hi)
{
return DivisibleBy5From0To(hi) - DivisibleBy5From0To(lo - 1);
}
对于可能不是正面的论点,您需要使用Math.Floor(n / 5.0)
代替n / 5
。
答案 1 :(得分:4)
也许:
int numMod5Between = Enumerable.Range(first, second - first + 1)
.Where(i => i % 5 == 0)
.Count();
答案 2 :(得分:3)
Console.WriteLine(Enumerable.Range(min,max-min+1).Count(n => n % 5 == 0));
答案 3 :(得分:2)
int total = 0;
for (int i = min; i <= max; i++)
{
if (i % 5 == 0)
{
total = total + 1;
}
}
//print total
答案 4 :(得分:2)
这很容易,当你在for循环中有特殊情况时,只需在其中增加一个计数器。
Console.Write("Enter min: ");
int min = int.Parse(Console.ReadLine());
Console.Write("Enter max: ");
int max = int.Parse(Console.ReadLine());
Console.WriteLine("The numbers devidable by 5 without remainder from {0} to {1} are: ",min,max);
int count = 0;
for (int i = min; i <= max; i++)
{
if (i % 5 == 0)
{
Console.WriteLine(i);
count++;
}
}
Console.WriteLine("Total number dividable by 5 is: " + count.ToString());
答案 5 :(得分:1)
int count=0;
Console.Write("Enter min: ");
int min = int.Parse(Console.ReadLine());
Console.Write("Enter max: ");
int max = int.Parse(Console.ReadLine());
Console.WriteLine("The numbers devidable by 5 without remainder from {0} to {1} are: ",min,max);
for (int i = min; i <= max; i++)
{
if (i % 5 == 0)
{
count++;
}
}
Console.WriteLine(count);
您添加count
变量,将其设置为0并在找到可撤销的数字时将其增加,最后打印count
。
答案 6 :(得分:1)
Console.Write("Enter min: ");
int min = int.Parse(Console.ReadLine());
Console.Write("Enter max: ");
int max = int.Parse(Console.ReadLine());
Console.WriteLine("The numbers devidable by 5 without remainder from {0} to {1} are: ",min,max);
int count = 0;
for (int i = min; i <= max; i++)
{
if (i % 5 == 0)
{
Console.WriteLine(i);
count++;
}
}
Console.WriteLine(count);
新行int count = 0;
和count++;
后跟Console.WriteLine(count);
。逻辑是每次i % 5 == 0
为真,那么你增加计数。
答案 7 :(得分:0)
Console.Write("Enter min: ");
int min = int.Parse(Console.ReadLine());
Console.Write("Enter max: ");
int max = int.Parse(Console.ReadLine());
Console.WriteLine("The numbers dividable by 5 without remainder from {0} to {1} are: ", min, max);
for (int i = min; i <= max; i++)
{
if (i % 5 != 0)
continue;
Console.WriteLine(i);
这是使用continue statement.cheers
解决此问题的另一种方法