用户必须提供起点并指明序列应该是升序还是降序。到目前为止它开始计数并且永不停止。如何在将其递增10之后使其停止。我是否会使用if语句让用户选择使其升序或降序?
class Program
{
static void Main(string[] args)
{
int val;
Console.WriteLine("Please enter a number!");
val = Int32.Parse(Console.ReadLine());
for (int i = val; i <= (val + 10); val++)
Console.WriteLine(val);
Console.ReadLine();
}
}
答案 0 :(得分:7)
它永远不会因为你增加val
而停止,i
总是会小于val + 10
(你永远不会增加i
)。您应该增加i
,并在循环中使用i
。
static void Main(string[] args)
{
int val;
Console.WriteLine("Please enter a number!");
val = Int32.Parse(Console.ReadLine());
for (int i = val; i <= (val + 10); i++)
Console.WriteLine(i);
Console.ReadLine();
}
对于升序与降序部分,您还需要从用户那里获取第二个输入,如果他选择降序,请创建一个循环来检查i >= (val - 10)
是否为i--
每次迭代代替。
答案 1 :(得分:1)
using System;
using System.Linq;
class Sample {
static void Main(){
const char down = '-';
Console.Write("Please enter a number! n[{0}]:", down);
string input = Console.ReadLine();
char ch = input.Last();
int diff = (ch == down) ? -1 : 1;
int val = Int32.Parse(input.TrimEnd(down));
for(var i = 1; i <= 10; i++, val += diff)
Console.WriteLine(val);
}
}
<强>样本强>
Please enter a number! n[-]:10-
10
9
8
7
6
5
4
3
2
1
Please enter a number! n[-]:5
5
6
7
8
9
10
11
12
13
14
答案 2 :(得分:0)
更改为:
static void Main(string[] args)
{
int val;
Console.WriteLine("Please enter a number!");
val = Int32.Parse(Console.ReadLine());
for (int i = val; i <= (val + 10); i++)
Console.WriteLine(i);
Console.ReadLine();
}
答案 3 :(得分:0)
static void Main(string[] args)
{
int val, isDecrement;
Console.WriteLine("Please enter a number!");
val = Int32.Parse(Console.ReadLine());
Console.WriteLine("Please enter 1 to go Descending order!");
isDecrement = Int32.Parse(Console.ReadLine());
if(isDecrement ==1)
{
for (int i = val; i >= (val - 10); i--)
Console.WriteLine(i);
}
else
{
for (int i = val; i <= (val + 10); i++)
Console.WriteLine(i);
}
Console.ReadLine();
}