发现C程序,如果一个数字是回文与否 [英] C program to find if a number is palindrome or not

查看:253
本文介绍了发现C程序,如果一个数字是回文与否的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了一个C程序来检查,如果一个数是回文与否。我用下面的code,但它表明像12321非回文数。能否请您解释我在下面的程序中的错误?

 的#include<&stdio.h中GT;
诠释的main()
{
    INT I,X,N,C,J;
    INT D = 0;
    的printf(请输入数字中的总位数:);
    scanf函数(%d个,&安培; I)
    的printf(\\ n输入数字:);
    scanf函数(%d个,&安培; N);
    J = N;
    为(X = 1; X&下; = I; X ++)
    {
       ç= j的10%;
       D = C *(10 ^(I-X))+ D;
       J =(J-C)/ 10;
    }
    如果(D == N)
    {
        的printf(\\ npalindrome);
    }
    其他
    {
        的printf(\\ n非回文);
    }
    返回0;
}


解决方案

这个算法是人类思维的简单,它的工作原理

 的#include<&stdio.h中GT;
诠释主(){
    INT I = 0,N,确定= 1;
    字符的buff [20];
    的printf(请输入一个整数:);
    scanf函数(%d个,&安培; N); //我正在ommiting错误检查    N = sprintf的(BUFF,%D,N); //将其转换为字符串,并获得在结果LEN
    如果(正2)返回0;    I = N / 2;
    N--;
    而(I和;&安培; OK){
        一世 - ;
        //的printf(%C ==%C%S \\ n,BUFF [I],BUFF [N-1],(BUFF [I] == BUFF [N-1])真:假);
        确定与放大器; =(抛光轮[I] ==抛光轮[N-1]);    }    的printf(%s是%spalindrome \\ n,浅黄色,确定:不?);
    返回0;
}

I made a C program to check if a number is palindrome or not. I used the following code, but it shows numbers like 12321 as non palindrome. Can you please explain me the mistake in the program below?

#include <stdio.h>
int main()
{
    int i, x, n, c, j;
    int d=0;
    printf ("enter total digits in number: ");
    scanf ("%d", &i);
    printf ("\nenter number: ");
    scanf ("%d", &n);
    j=n;
    for (x=1; x<=i; x++)
    {
       c= j%10;
       d=c*(10^(i-x))+d;
       j=(j-c)/10;
    }
    if (d==n)
    {
        printf ("\npalindrome");
    }
    else
    {
        printf ("\nnon palindrome");
    }
    return 0;
}

解决方案

this algorithm is as simple as human thinking, and it works

#include <stdio.h>


int main() {
    int i=0,n,ok=1;
    char buff[20];


    printf("Enter an integer: ");
    scanf("%d", &n); // i am ommiting error checking

    n=sprintf(buff,"%d",n); //convert it to string, and getting the len in result
    if(n<2) return 0;

    i=n/2;
    n--;
    while(i && ok) {
        i--;
        //printf("%c == %c %s\n", buff[i],buff[n-i],(buff[i]==buff[n-i])?"true":"false");
        ok &= (buff[i]==buff[n-i]);

    }

    printf("%s is %spalindrome\n",buff, ok?"":"not ");
    return 0;
}

这篇关于发现C程序,如果一个数字是回文与否的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆