试图找到回文年,我正在倒转并将一个整数切成两半,但只有前半部分会填满

Trying to find palindrome years, I'm reversing and cutting an int in half, but only the first half would fill

看下面的代码。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int isPalindromePossible(int);
unsigned concatenate(unsigned, unsigned);
int jour, mois, annee, jm, length, leng, begin, end;
char str[12], str2[12], revstr[40];

int main() {
    printf("Entrez le jour : ");
    scanf("%d", &jour);
    printf("Entrez le mois : ");
    scanf("%d", &mois);
    printf("Entrez l'annee : ");
    scanf("%d", &annee);

    int test = reverse(annee);
    isPalindromePossible(annee);
    
    return 0;
}

int isPalindromePossible(int year) {
    int firstHalf;
    int secondHalf;
    
    while (year > 0) {
        int digit = year % 10;
        printf("YEAR = %d\n", year);
        if (year <= 99) {
            concatenate(secondHalf, digit);
        } else {
            concatenate(firstHalf, digit);
        }
        year = year / 10;
    }
    
    printf("FH = %d, SH = %d", firstHalf, secondHalf);
    
    return 0;
}

unsigned concatenate(unsigned x, unsigned y) {
    unsigned pow = 10;
    while(y >= pow)
        pow *= 10;
    return x * pow + y;        
}

The code was ran, and output this.

看看下半部分如何永远不会被填满,即使 if 语句有效。摸不着头脑,想不通。

如果您看到问题,我将不胜感激。

非常感谢。

firstHalfsecondHalf都没有初始化就使用了。您通过使用不确定的未初始化非静态局部变量的值调用了未定义的行为

你必须

  • 将它们初始化为零。
  • 将它们更新为 concatenate 的 return 值。
int isPalindromePossible(int year) {
    int firstHalf = 0;
    int secondHalf = 0;
    
    while (year > 0) {
        int digit = year % 10;
        printf("YEAR = %d\n", year);
        if (year <= 99) {
            secondHalf = concatenate(secondHalf, digit);
        } else {
            firstHalf = concatenate(firstHalf, digit);
        }
        year = year / 10;
    }
    
    printf("FH = %d, SH = %d", firstHalf, secondHalf);
    
    return 0;
}

另一种解决方案(去掉concatenate的过程):

int isPalindromePossible(int year) {
int firstHalf = 0;//initialize at 0
int secondHalf = 0;//initialize at 0

int l =(int)log10((double)year)+1;//calculate the number of digits of year
int s=0;

// while loop for finding the mirror of year
while (year > 0)
{
    int digit = year % 10;
    s=s*10+digit;
    printf("\n%d\n",year);
    year = year / 10;
}
 
 firstHalf=s%(int)round (pow(10,(double)l/2));//first part of number
 secondHalf=s/(int)round (pow(10,(double)l/2));//Second part of number

 printf("\nFH = %d, SH = %d", firstHalf, secondHalf);

return 0;

}