问题
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