C# 4.0 如何编写迭代2,-3,4,-5的序列?
我想编写一个程序,使用控制台应用程序打印100个序列成员,如2,-3,4,-5 但我没有使用循环 请帮助我。构建序列:C# 4.0 如何编写迭代2,-3,4,-5的序列?,c#-4.0,console-application,C# 4.0,Console Application,我想编写一个程序,使用控制台应用程序打印100个序列成员,如2,-3,4,-5 但我没有使用循环 请帮助我。构建序列: public IEnumerable<int> Sequence() { int current = 0; int sign = 1; while(true) { current++; sign *= -1; yield return current * sign; } } 下面是另一个简单函数:
public IEnumerable<int> Sequence()
{
int current = 0;
int sign = 1;
while(true)
{
current++;
sign *= -1;
yield return current * sign;
}
}
下面是另一个简单函数:
static void Main(string[] args)
{
for(int i = 0; i <=100; i++)
{
Console.Write(AlternatingSignSequence(i).ToString() + " ");
}
Console.ReadLine();
}
static int AlternatingSignSequence(int input)
{
return ((input % 2 == 0) ? 1 : -1) * input;
}
但我没有用循环为什么不呢?这是显而易见的方法…如果这是家庭作业,那么它就会有意义。这不是我的家庭作业,我的答案是。非常感谢。
static void Main(string[] args)
{
int current;
int sign = 1;
int result;
for (current = 1; current <= 100; ++current)
{
sign *= -1;
result = current * sign;
Console.WriteLine(result);
}
Console.ReadLine();
}
static void Main(string[] args)
{
for(int i = 0; i <=100; i++)
{
Console.Write(AlternatingSignSequence(i).ToString() + " ");
}
Console.ReadLine();
}
static int AlternatingSignSequence(int input)
{
return ((input % 2 == 0) ? 1 : -1) * input;
}