这是我的代码, 我的代码中有很多东西需要改进,但我现在关注的是阻止程序崩溃。 提前谢谢!
#include <stdio.h>
int IsPalindrome(int a);
int dec[20];
int a = 0;
int main()
{
printf("Please insert your number:\n");
scanf("%d", a);
IsPalindrome(a);
return 0;
}
int IsPalindrome(int a)
{
int temp = 0;
int count = 1;
int p = 1;
temp = a;
while(temp > 10)
{
dec[count] = temp % 10;
count = count+1;
temp = temp / 10;
printf("%d", count);
}
for(int i = 1; i < count; i++)
{
if (dec[i] != dec[count-i])
{
printf("Your number is not a Palindrome");
return 1;
}
}
}
附带问题:
答案 0 :(得分:1)
int a = 0; scanf("%d", a);
会导致粉碎,因为这意味着它应该将数据存储到无效的地方。void
的返回类型。请注意,根据标准,main()
的返回类型应为int
。试试这个:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define BUFFER_SIZE 512
char* ReadNumber(void);
void IsPalindrome(const char* a);
int main(void)
{
char* a;
printf("Please insert your number:\n");
a = ReadNumber();
IsPalindrome(a);
free(a);
return 0;
}
char* ReadNumber(void) {
char* ret = malloc(BUFFER_SIZE);
size_t allocatedSize = BUFFER_SIZE;
size_t readLen = 0;
if (ret == NULL)
{
perror("malloc");
exit(1);
}
for (;;)
{
int c = getchar();
if (!isdigit(c))
{
if (c != EOF) ungetc(c, stdin);
break;
}
ret[readLen++] = c;
if (readLen >= allocatedSize)
{
ret = realloc(ret, allocatedSize += BUFFER_SIZE);
if (ret == NULL)
{
perror("realloc");
exit(1);
}
}
}
ret[readLen] = '\0';
return ret;
}
void IsPalindrome(const char* a)
{
size_t count = strlen(a);
/* can't write as i < count - i - 1 because size_t may be unsigned */
for(size_t i = 0; i + i + 1 < count; i++)
{
if (a[i] != a[count - i - 1])
{
printf("Your number is not a Palindrome");
return;
}
}
}
答案 1 :(得分:0)
另一种解决方案是将数字作为字符串读取。然后反转字符串,看看反向字符串是否按字典顺序等于原始字符串。
void strrev(char *s)
{
char *start, *end;
start = s;
end = s + strlen(s) - 1;
for (; end > start; --end, ++start) {
char tmp;
tmp = *start;
*start = *end;
*end = tmp;
}
}
/* checks if string is a number. Only positive integers, or 0 */
int isnum(const char *s)
{
int i;
for (i = 0; s[i]; ++i)
if (!isdigit(s[i]))
return 0;
return 1;
}
int main()
{
char num[16], rev[16];
fgets(num, 16, stdin);
if (!isnum(num)) {
fprintf(stderr, "not number\n");
return 1;
}
strcpy(rev, num);
strrev(rev);
if (strcmp(rev, num) == 0)
fprintf(stderr, "Palindrome\n");
else fprintf(stderr, "No\n");
}