问题
Trying to write a code that finds the location (index) of one number inside another. For example, num1=1948 , num2=94 the index will be 2. Can some one please tell me what i did wrong? thank you!
int num1, num2, index=0;
printf("Please enter a number: \n\n");
scanf_s("%d", &num1);
printf("\n\nPlease enter another number: \n\n");
scanf_s("%d", &num2);
int temp1 = num1;
int temp2 = num2;
while (temp1 != 0 || temp2 != 0)
if (temp1 % 10 == temp2 % 10)
{
temp1 = temp1 / 10;
temp2 = temp2 / 10;
index++;
}
else temp1 = temp1/10;
if (index != 0)
printf("%d\n\n\n", index);
else printf("no");
system("pause");
return 0;
回答1:
One of the best way to find out what's wrong in your code is to debug it, using a debugger or just adding some printf in your code. For example, you can print out the values of temp1, temp2 and index every time you (re)enter the while loop. i.e.
while (temp1 != 0 || temp2 != 0) {
// Add this to find out what the values are in these variables
printf("temp1=%-6d, temp2=%-6d, index=%2d\n", temp1, temp2, index);
if (temp1 % 10 == temp2 % 10)
{
temp1 = temp1 / 10;
temp2 = temp2 / 10;
index++;
}
else
{
temp1 = temp1/10;
}
}
What I can see so far is that when there is an unmatch of temp1 % 10 and temp2 % 10, the temp2 variable is not being reset to the value num2. For example if you have temp1 = 12323 and temp2 = 123, the states would be as follow:
|--temp1--|--temp2--|--index--|
| 12323 | 123 | 0 |
| 1232 | 12 | 1 |
| 123 | 1 | 2 |
| 12 | 1 | 2 | <-- You would want temp2 to reset to 123 and
| 1 | 1 | 2 | compare again
| 0 | 0 | 3 |
PS: The KMP algorithm is doing this job, in string (char array)
来源:https://stackoverflow.com/questions/59009753/finding-the-index-of-num1-inside-num2