以下代碼需要檢查迴文並使用遞歸向後寫入用戶輸入,然後使用相同的方法找到最大公用分母。找到gcd的代碼部分,告訴它是否是一個迴文序列,但每當它得到它反轉代碼的部分時,它就會崩潰。爲什麼每次都會崩潰。使用遞歸的迴文
#include <stdio.h>
#include <stdlib.h>
/*Delare the prototypes*/
char palindromes(char[], int);
char backwards(char[], int, int);
int gcdfunc(int, int);
int findgcd(int, int);
int main()
{
char userinput[10];/*Declares the character array for the input*/
int index= 0;/*Index for the counting loop*/
int counter= 0;/*Counts number of elements entered in the array*/
int printindex= 0;/*Index to print the values on the screen*/
int gcd= 0;/*Sets a value for the GCD*/
int palcheck = 0;
int value1= 0;/*User value 1*/
int value2= 0;/*User value 2*/
int flipindex=0;/*Sets an index for the gcd function*/
printf("Please enter a series of nine or less characters to test for a palindrome.\n");
scanf(" %9s%n", &userinput, &counter);
printf("\n");
palcheck = palindromes(userinput, counter-1);
if(palcheck == 0)
{
printf("Your input was not a palindrome \n");
}/*End of if statement*/
else
{
printf("Your input was a palindrome \n");
}/*End of else statement*/
backwards(userinput, counter-1, flipindex);
printf("Your input backwards is: ");
for(printindex; printindex <= counter; printindex++)
{
printf("%c", userinput[printindex]);
}/*End of printing backwards loop*/
printf("\n");
printf("\nEnter two numbers: ");
scanf("%d %d",&value1,&value2);
gcd=gcdfunc(value1, value2);
printf("The GCD of %d and %d is: %d",value1,value2,gcd);
system("pause");
}/*End of main function*/
char palindromes(char userinput[], int counter)
{
int palindex= 0;/*Declares the index to check for a palindrome*/
int palendinx= counter;
int modulus = counter%2;
if(modulus = 0)
{
if(userinput[palindex]==userinput[palendinx])
{
palindex++;
palendinx--;
if(palindex==(counter/2) && userinput[palindex]==userinput[palendinx])
return 1;
palindromes(userinput, counter);
}
else
{
return 0;
}
}
else
{
if(userinput[palindex]==userinput[palendinx])
{
palindex++;
palendinx--;
if(palindex==(counter/2) && userinput[palindex]==userinput[palendinx])
return 1;
palindromes(userinput, counter);
}
else
{
return 0;
}
}
}/*End of palidrome function*/
char backwards(char userinput[], int counter, int flipindex)
{
while(flipindex<(counter/2))
{
char temp;/*Sets a temporary value to swap the two values*/
temp = userinput[flipindex];
userinput[flipindex] = userinput[counter-flipindex];
userinput[counter-flipindex] = temp;
backwards(userinput, counter, flipindex++);
}
}/*End of reverse function*/
int gcdfunc(int value1, int value2)
{
int gcd;
gcd=findgcd(value1,value2);
return gcd;
}
int findgcd(int value1,int value2)
{
while(value1!=value2)
{
if(value1>value2)
return findgcd(value1-value2,value2);
else
return findgcd(value1,value2-value1);
}
return value1;
}
您可以使用GDB並在不會導致崩潰的行上縮小範圍。 – brokenfoot