首页 > 代码库 > for语句应用举例140819
for语句应用举例140819
1、求阶乘
Console.WriteLine("输入一个数");
int n = Convert.ToInt32(Console.ReadLine());
int s = 1;
for (int i = 1; i <= n; i++)
{
s = s * i;
}
Console.WriteLine("结果:" + s);
例:5!
2、求阶乘的和
Console.WriteLine("输入一个数:");
int n = Convert.ToInt32(Console.ReadLine());
int a = 0;
for (int i = 1; i <= n; i++)
{
int s = 1;
for (int j = 1; j <= i; j++)
{
s = s * j;
}
a = a + s;
}
Console.WriteLine("结果:" + a);
例:5!+4!+3!+2!+1!=
3、找出100以内质数,并求和
int sum=0;
for (int i = 2; i <= 100; i++)
{
int a = 0;
for (int j = 1; j <= i; j++)
{
if (i % j == 0)
{
a++;
}
}
if (a == 2)
{
sum = sum + i;
Console.Write(i + "\t");
}
}
Console.Write("总和:"+sum);
4、100元购物券买香皂(2元)、牙刷(5元)、洗发水(15元),每样至少买一个,正好花光,求所有可能
int n = 1;
for (int i = 1; 2 * i < 100; i++)
{
for (int j = 1; 5 * j < 100; j++)
{
for (int k = 1; 15 * k < 100; k++)
{
if (2 * i + 5 * j + 15 * k == 100)
{
Console.WriteLine(n);
Console.WriteLine("香皂:" + i);
Console.WriteLine("牙刷:" + j);
Console.WriteLine("洗发水:" + k);
n++;
}
}
}
}
5、公鸡2文,母鸡1文,小鸡半文,每种至少买一只,100文钱买100只鸡,求所有可能
int n = 1;
for (int i = 1; 2 * i < 100; i++)
{
for (int j = 1; j < 100; j++)
{
for (int k = 1; 0.5 * k < 100; k++)
{
if (2 * i + j + 0.5 * k == 100 && i + j + k == 100)
{
Console.WriteLine(n);
Console.WriteLine("公鸡{0}只,母鸡{1}只,小鸡{2}只", i, j, k); //"{0}",占位符,必须从0开始
n++;
}
}
}
}