2015-11-19 62 views
1

我做了一個C程序來檢查一個數是否是迴文數。我使用了下面的代碼,但它顯示的數字如12321非迴文。你能否在下面的程序中解釋我的錯誤?C程序找到一個數是否是迴文數

#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; 
} 
+2

'^'是C中的異或運算符。 – BLUEPIXY

+0

您還沒有檢查過'scanf'調用的返回值。你怎麼知道他們成功了? – user694733

+0

你能用簡單的話來詳細說明嗎? – dreadedHarvester

回答

1

^是xor操作符。

爲了提高功率,你需要包括math.h並調用pow

d = (c * pow(10, i - x)) + d; 
1

這個算法是人類思維的簡單,它的工作原理

#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; 
} 
+0

如何刪除'scanf(「%d」,...)/ sprintf'的東西,只是做'scanf(「%s」,buf);'相反...? ;) – CiaPan

+0

起初它是這樣,但我改變它遵循他的源代碼。因爲他正在處理整數 – milevyo

0
// Yet another way to check for palindrome. 
#include <stdio.h> 
#include <stdlib.h> 

int main(int argc, char **argv) 
{ 
    int n, rn, tn; 
    printf("Enter an integer: "); 
    scanf("%d", &n);  

    // reverse the number by repeatedly extracting last digit, add to the 
    // previously computed partial reverse times 10, and keep dropping 
    // last digit by dividing by 10 
    for (rn = 0, tn = n; tn; tn /= 10) rn = rn * 10 + tn % 10; 
    if (rn == n) printf("%d is palindrome\n", n); 
    else printf("%d is not palindrome\n", n); 
} 
0

環路像這可能會:

int src;  // user input 
int n;  // no of digits 
int res = 0; 
int tmp;  // copy of src 

// .... read the input: n and src .... 

tmp = src; 
for(int i = 0; i < n; i ++) 
{ 
    int digit = tmp % 10; // extract the rightmost digit 
    tmp /= 10;    // and remove it from source 
    res = 10*res + digit; // apend it to the result 
} 

// ...and test if(res == src)... 
相關問題