在num2中查找num1的索引 [英] finding the index of num1 inside num2
问题描述
尝试编写代码以查找一个数字在另一个数字内的位置(索引). 例如,num1 = 1948,num2 = 94 索引将是2. 有人可以告诉我我做错了什么吗? 谢谢!
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;
推荐答案
找出代码错误的最佳方法之一是使用调试器或仅在代码中添加一些printf
对其进行调试.例如,每次(重新)进入while
循环时,都可以打印出temp1
,temp2
和index
的值.即
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;
}
}
到目前为止,我看到的是temp1 % 10
和temp2 % 10
不匹配时,temp2
变量不会重置为值num2
.例如,如果您有temp1 = 12323
和temp2 = 123
,则状态如下:
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: KMP 算法正在执行此任务,字符串形式(char数组)
PS: The KMP algorithm is doing this job, in string (char array)
这篇关于在num2中查找num1的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!