gpt4 book ai didi

C:检查3位数字是否是回文数

转载 作者:行者123 更新时间:2023-11-30 21:29:04 24 4
gpt4 key购买 nike

所以我编写了一个程序,从用户那里获取一个 3 位数字并检查它是否是回文:

#include <stdio.h>
#include <stdlib.h>
int isPalindromic(char q, char w, char e);
int main()
{
int res;
char a,b,c;

printf("Give me a three digit number\n");
scanf("%c %c %c", &a, &b, &c);
res = isPalindromic(a,b,c);

if (res == 1)
printf("damn son that's palindromic how u do dat u a haker!!!\n");
else
printf("B O O O L O S E R\n");

system("pause");
return 0;
}

int isPalindromic(char q, char w, char e)
{
int result;
if (q == e)
result = 1;
else
result = 0;
return result;
}

由于懒惰,我想到了将每个数字当作一个字符而不是整数,然后isPalindromic函数比较第一个数字和第三个数字。

它的作用就像一个魅力,但它有什么弱点或什么吗?我做错了什么吗?

最佳答案

您可以通过编写一个检查任何字符串是否为回文的函数来使程序更加通用:

int ispal(const char *s)
{
int start, mid, end;

mid = strlen(s) / 2;
end = strlen(s) - 1;

for (start = 0; start < mid; ++start, --end)
if (s[start] != s[end])
return 0; /* not palindrome */

if (start == mid)
return 1; /* palindrome */
}

然后,您可以检查用户输入是否为 3 位数字(isdigitstrlen),并且仅当是时,才将其作为输入传递给 ispal 函数。这种通用方法使您的应用程序将来更具可扩展性。

编辑:不要使用system("pause"),因为并非所有系统都支持pause命令。

关于C:检查3位数字是否是回文数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34838821/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com