我在写这个练习时遇到了问题。 这应该评估一个给定的数组是否包含一个回文数字序列,程序正确构建但不运行(控制台仍为黑色)。我错在哪里?谢谢大家的帮助!
#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;
}
P.S。 如何在代码块上激活调试器“监视”以查看其他功能变量? (我停止了主要功能)
答案 0 :(得分:0)
while (p) {
循环。这里有无限循环(你有它!),因为如果你不改变p
,这个循环永远不会停止。size
的实施中混合SIZE
和palindrome()
(mid
是size
的一半,但整个循环来自0
} SIZE-1
)。int p = 1;
的实施开始时移动palindrome()
(并从其参数列表中移除int p
)。答案 1 :(得分:0)
试试这个:
int palindrome(const int a[], int p, int size)
{
int mid, j;
mid = size / 2;
for (j = 0; j < (size / 2); j++){
if (a[mid + (j + 1)] != a[mid - (j + 1)]);
p = 0;
break;
}
}
return p;
}
答案 2 :(得分:0)
这里有一个没有p
的替代方案palindrome
返回0
或1
int palindrome(const int a[], int size)
{
int j , k , ret;
for (j = 0 , k = size - 1 ; j < k; j++ , k--)
{
if (a[j)] != a[k])
{
ret = 0;
break;
}
}
if(j >= k)
ret = 1;
return ret;
}
您可以在palindrome
中的if
语句中拨打main
,如下所示:
if(palindrome(a , SIZE))
printf("\nseries is palindrome\n");
else
printf("\nseries isn't palindrome\n");