What's wrong with this c program? Debugging it suggests that the program is struck at while (sqroot != 0); [duplicate]

余生长醉 提交于 2019-12-10 23:58:18

问题


Here's a screenshot of debugging process
I am learning to program in C. I am trying to find if a number is a mirror image or not, But the program compiles error-free yet didn't give the desired result. Debugging the program shows that it struck at while (sqroot != 0);

    // Mirror number
    #include <stdio.h>
    #include <math.h>
    int main() {
            int num, rev1, rev2, rem1, rem2, sqr, sqroot;
            printf("Enter a number\n");
            scanf("%d", & num);
            sqr = pow(num, 2);
            while (sqr != 0) {
                    rem1 = sqr % 10;
                    rev1 = rev1 * 10 + rem1;
                    sqr = sqr / 10;

            }
            sqroot = sqrt(rev1);

            while (sqroot != 0); {
                    rem2 = sqroot % 10;
                    rev2 = rev2 * 10 + rem2;
                    sqroot = sqroot / 10;
            }

            if (rev2 == num)
                    printf("number is mirror");
            else
                    printf("Not a mirror number");

            return 0;
    }

回答1:


while (sqroot != 0); { ... } is an infinite loop. because the ; is considered as an empty instruction. An instruction (empty or not) just after an if (condition) or a while (condition) is considered to be the only instruction of the if, while, for scope.

It is the same than writting

while (sqroot != 0)
{
    ; /* Do nothing */
}
/* The scope below doesn't belong to the while */
{
    rem2 = sqroot % 10;
    rev2 = rev2 * 10 + rem2;
    sqroot = sqroot / 10;
}

Remove the ; and this problem should be solved.

while (sqroot != 0) {
    rem2 = sqroot % 10;
    rev2 = rev2 * 10 + rem2;
    sqroot = sqroot / 10;
}



回答2:


Initialize to rev1=0 and rev2=0.Because without a initial value,rev1 and rev2 will contain garbage values so that run time error will occur.



来源:https://stackoverflow.com/questions/52610522/whats-wrong-with-this-c-program-debugging-it-suggests-that-the-program-is-stru

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