c语言 - 试图找到回文年份,我正在反转并将一个 int 切成两半,但只有前半部分会填充



请参阅以下代码。

#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 = %dn", 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;        
}

代码已运行,并输出此代码。

看看下半场是如何从不被填满的,即使if语句有效。我在挠头,不知道为什么。

如果你看到这个问题,我将不胜感激。

非常感谢。

firstHalfsecondHalf都在未初始化的情况下使用。您通过使用未初始化的非静态局部变量的值来调用未定义的行为,这些变量是不确定的。

你必须

  • 将它们初始化为零
  • 更新它们以返回concatenate的值
int isPalindromePossible(int year) {
int firstHalf = 0;
int secondHalf = 0;

while (year > 0) {
int digit = year % 10;
printf("YEAR = %dn", 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;
}

另一个解决方案(删除连接过程(:

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%dn",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;
}

最新更新