Fixing a broken loop by changing exactly one chara

2019-01-16 16:25发布

I found a site with some complicated C puzzles. Right now I'm dealing with this:

The following is a piece of C code, whose intention was to print a minus sign 20 times. But you can notice that, it doesn't work.

#include <stdio.h>
int main()
{
    int i;
    int n = 20;
    for( i = 0; i < n; i-- )
        printf("-");
    return 0;
}

Well fixing the above code is straight-forward. To make the problem interesting, you have to fix the above code, by changing exactly one character. There are three known solutions. See if you can get all those three.

I cannot figure out how to solve. I know that it can be fixed by changing -- to ++, but I can't figure out what single character to change to make it work.

8条回答
倾城 Initia
2楼-- · 2019-01-16 17:11

Here is another one:

#include <stdio.h>

int main()
{
    int i;
    int n = -20; //make n negative
    for( i = 0; i < n; i-- ) 
        printf("-");
    return 0;
}
查看更多
Fickle 薄情
3楼-- · 2019-01-16 17:17

Third answer:

for( i = 0; i + n; i-- )  
    printf("-"); 

Thanks to Gab Royer for inspiration.

Explanation: Eventually , i + n will result in -20 + 20 = 0 which is false.

查看更多
登录 后发表回答