Fixing a broken loop by changing exactly one character

送分小仙女□ 提交于 2019-11-28 04:32:19

Here is one solution:

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

Here is a second one, thanks to Mark for helping me!

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

And Mark also had the third one which is

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

Change i-- to n-- is another.

Okay - Gab made the fix, so I removed the other solution. He wins!

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.

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

Changed i-- to n--

Here's one of them, I think:

for( i = 0; i < n; n-- )

The comparison in the for loop can be any expression - you can negate i.

for (i = 0; -i < n ; i--)

Solution 1

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

Solution 2

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

Haven't figured a third.

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;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!