我在编写此练习时遇到问题。 这应该评估给定的数组是否包含回文数字序列,程序正确构建但不运行(控制台保持黑色)。我在这件事上哪里错了?感谢您的帮助!
#include <stdio.h>
#include <stdlib.h>
#define SIZE 15
//i'm using const int as exercise demand for it
//should i declare size as int when giving it to function? also if it's been declared?
//i'm a bit confused about that
int palindrome(const int a[], int p, int size);
int main()
{
int a[SIZE] = {0, 1, 2, 3, 4, 5, 6, 7, 6, 5, 4, 3, 2, 1, 0};
int p = 1; //i'm not using boolean values, but i think should work anyway, right?
p = palindrome(a, p, SIZE);
if (p)
printf("\nseries is palindrome\n");
else
printf("\nseries isn't palindrome\n");
return 0;
}
int palindrome(const int a[], int p, int size)
{
int mid, j;
mid = size / 2;
while (p) {
for (j = 0; j < (SIZE / 2); j++){
if (a[mid + (j + 1)] != a[mid - (j + 1)]) //i think i might be wrong on this, but don't know where i'm in fault
p = 0;
}
}
return p;
}
附: 如何激活代码块上的调试器“监视”以查看其他函数变量? (我停止了主要功能)
最佳答案
- 您不需要
while (p) {
循环。这里可能会出现无限循环(并且您已经遇到了!),因为如果您不更改p
,则此循环永远不会停止。 - 在
palindrome()
的实现中混合size
和SIZE
(mid
是的一半>size
,但整个循环是从0
到SIZE-1
)。 - 此外,最好在
palindrome()
的实现开始时移动int p = 1;
(并删除int p
来自其参数列表)。
关于c - 回文检查算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24350181/