为什么这个代码只输出""? (Codeingame&#s; Thor挑战)

时间:2017-04-11 12:59:17

标签: c++

我需要通过代码名称的Thor-challenge上的x和y值的不同来找到我用替代方法所犯的错误。

以下是游戏循环的代码:

// game loop
    while (1) {
        int remainingTurns; // The remaining amount of turns Thor can move. Do not remove this line.
        cin >> remainingTurns; cin.ignore();
        int difx = lightX-initialTX;
        int dify = lightY-initialTY;
        float mathquot=dify/difx;
        string out ="";
        if(difx==0 || dify==0){
            if(difx=0){
                if(dify<0) out="W"; initialTY-=1;
                if(dify>0) out="E"; initialTY+=1;
            }
            if(dify=0){
                if(difx<0) out="N"; initialTX-=1;
                if(difx>0) out="S"; initialTX+=1;
            }
        }else{
            if(mathquot>0 && (difx>0 && dify>0)) out="SE"; initialTY +=1; initialTX+=1;
            if(mathquot>0 && (difx<0 && dify<0)) out="NW"; initialTY -=1; initialTX-=1;
            if(mathquot<0 && difx<0) out="SW";  initialTY +=1; initialTX-=1;
            if(mathquot<0 && dify<0) out="NE";  initialTY -=1; initialTX+=1;
        }
        // Write an action using cout. DON'T FORGET THE "<< endl"
        // To debug: cerr << "Debug messages..." << endl;


        // A single line providing the move to be made: N NE E SE S SW W or NW
        cout << out << endl;
    }

1 个答案:

答案 0 :(得分:1)

一个问题是你似乎有很多缺失的大括号,大概是因为你决定在一行上放多个语句,所以例如。

        if(mathquot>0 && (difx>0 && dify>0)) out="SE"; initialTY +=1; initialTX+=1;

应该是:

        if(mathquot>0 && (difx>0 && dify>0)) { out="SE"; initialTY +=1; initialTX+=1; }

等等,对于其他类似的行。

<小时/> 您似乎也将赋值=)与等式测试(==)混淆,因此行如下:

if(difx=0)

应该是:

if(difx == 0)

<小时/> 另一个问题:您正在错误地混合整数和浮点运算。例如。在这一行:

float mathquot=dify/difx;

你在整数除法中执行截断,然后将其转换为浮点结果。你最有可能需要:

float mathquot=(float)dify/difx;

将迫使除法作为浮点执行。

<小时/> 重要提示:如果您启用了警告,编译器会选择上面的一些问题。如果您了解如何启用警告,您将节省大量时间和精力(例如{{ 1}}),然后在编译时注意任何此类警告。如果您的代码“干净地”编译(即没有警告),那么在运行时调试的问题应该更少。