替换循环

时间:2018-05-03 00:17:15

标签: c#

我正在尝试用c sharp编写一个程序,没有任何循环的决策语句,但我不知道如何摆脱for循环语句。

public int score()
{
    int scor = 0;
    int i=0;
    int type;
    for(int frameIndex=0; frameIndex < 10; frameIndex++)
    {
        type=Convert.ToInt32(isStrike(i));
        scor+=getStrikeCalculation(i)*type;
        i+=1*type;
        type=Convert.ToInt32(isSpare(i));
        scor+=getSpareCalculation(i)*type;
        i+=2*type;
        type=Convert.ToInt32(isNormal(i));
        scor += getNormalCalculation(i)*type;
        i+=2*type;
    }
    return scor;
}
private bool isNormal(int i)
{
    return rolls[i]+rolls[i+1]!=10 && rolls[i]!=10;
}
private bool isSpare(int i){
    return rolls[i] + rolls[i+1] == 10;
}
private bool isStrike(int i){
    return rolls[i] == 10;
}
private int getStrikeCalculation(int i){
    return rolls[i]+ rolls[i+1] + rolls[i+2];
}
private int getNormalCalculation(int i){
    return rolls[i]+rolls[i+1];
}
private int getSpareCalculation(int i){
    return rolls[i] + rolls[i + 1] + rolls[i + 2];
}

我尝试将分数递归,但它没有用,递归我不知道如何停止该功能,因为我不能使用if语句。

2 个答案:

答案 0 :(得分:6)

你的循环只做了十次。如果你不想要循环,那就做十次:

int scor = 0;
int i=0;
int type;
int frameIndex=0;
type=Convert.ToInt32(isStrike(i));
scor+=getStrikeCalculation(i)*type;
i+=1*type;
type=Convert.ToInt32(isSpare(i));
scor+=getSpareCalculation(i)*type;
i+=2*type;
type=Convert.ToInt32(isNormal(i));
scor += getNormalCalculation(i)*type;
i+=2*type;
frameIndex += 1;
type=Convert.ToInt32(isStrike(i));
scor+=getStrikeCalculation(i)*type;
i+=1*type;
type=Convert.ToInt32(isSpare(i));
scor+=getSpareCalculation(i)*type;
i+=2*type;
type=Convert.ToInt32(isNormal(i));
scor += getNormalCalculation(i)*type;
i+=2*type;
frameIndex += 1;
type=Convert.ToInt32(isStrike(i));
scor+=getStrikeCalculation(i)*type;
i+=1*type;
type=Convert.ToInt32(isSpare(i));
scor+=getSpareCalculation(i)*type;
i+=2*type;
type=Convert.ToInt32(isNormal(i));
scor += getNormalCalculation(i)*type;
i+=2*type;
frameIndex += 1;
... and so on, seven more times.

为什么你想要这样做是超出我的;循环的要点是避免将代码写出十次。你为什么要做这个奇怪的事情?只需写一个循环。

答案 1 :(得分:0)

您可以使用Enumerable.Range()

Enumerable.Range(0, 10).Select(frameIndex => {
    type=Convert.ToInt32(isStrike(i));
    scor+=getStrikeCalculation(i)*type;
    i+=1*type;
    type=Convert.ToInt32(isSpare(i));
    scor+=getSpareCalculation(i)*type;
    i+=2*type;
    type=Convert.ToInt32(isNormal(i));
    scor += getNormalCalculation(i)*type;
    i+=2*type;
});

当然,这里还有一个循环。它只是隐藏在别人写的方法背后,所以你不必在你自己的代码中看到它。但是,愚蠢的要求会带来愚蠢的解决方案。