在c#中将十进制数字循环1

时间:2014-08-05 14:51:55

标签: c# math

我想使用一次可能的操作将十进制数字循环1。

if x is 0 - 8 then x = x + 1
if x is 9 then x = 0

或相反的

if x is 1 - 9 then x = x - 1
if x is 0 then x = 9

有没有办法在一行代码中使用C#执行此操作?如果不是C#还有其他语言吗?

如果我想将它循环多于一个(2或3或其他),该怎么办?

3 个答案:

答案 0 :(得分:7)

我认为您正在寻找的是

var y = (x + 1) % 10;

这给出了:

x    y
------
0    1
1    2
...
8    9
9    0

递减

var y = (i + 9) % 10;

显然要更改金额,只需分别更改19

答案 1 :(得分:3)

int Cycle(int x)
{
    return x+1 % 10;
} 

int result = Cycle(0); // result is 1
int result = Cycle(8); // result is 9
int result = Cycle(9); // result is 0

答案 2 :(得分:1)

int Cycle(int x, int by = 1)
{
    return (x+by) % 10;
}

现在您可以致电Cycle(9, 3),这应该会给您2