我需要用C语言编写一个169算法的程序。但是,我似乎陷入了无限循环,直到程序崩溃。
对于任何自然数n
,“取反加”运算就是将n
的数字取反并添加
n
的值。例如,考虑 n = 345
。将其数字反转,我们得到数字 543
。现在我们必须添加n
到这个数字,即
n + 543 = 345 + 543 = 888
。对于大多数自然数来说,这个过程不断重复,最终会产生一个数字:
回文。例如号码59
产生序列 59
, 154
, 605
,和1111
,如(59 + 95) = 154
, (154 + 451) = 605
,和(605 + 506) = 1111
。该函数可以假设对该函数的初始调用始终使用一个数字来完成,该数字在某个时刻会获得一个回文数。
这是迄今为止的代码:
int invert_int(int n, int m) {
int div = n / 10; //Divide n by 10
if (div == 0)
return (n + m * 10); //If the division is equal to 0, then return n*+m*10
return (invert_int(div, n % 10 + m * 10)); //If not, calculate the inverse of it again
}
int calc(int num) {
int sum = 0; //Declare sum as 0
int inum = invert_int(num, 0); //Calculate the inverse of num by calling invert_int, having the number and 0 as parameters
//If num=inum, then it's a palindrome
if (num == inum) {
return sum; //Return sum to end
} else {
sum = num + inum; //sum = number + inverted number
printf("%d + %d = %d", num, inum, sum); //Print the previous sum
sum = sum + calc(num); //Add the next number to sum
return sum;
}
}
int main(int argc, char** argv) {
int input; //Declare variable to store the user's input
printf("Introduce a number:");
scanf("%d", &input); //Scan a number
printf("%d", calc(input)); //Print the result of the calculation by calling calc with 'input' as argument
return (EXIT_SUCCESS);
}
我似乎没有看到这里的问题。有人可以帮助我吗?预先感谢您。
最佳答案
您的calc
方法应该是
int calc(int num){
int sum = 0; //Declare sum as 0
int inum = invert_int(num,0); //Calculate the inverse of num by calling invert_int, having the number and 0 as parameters
//If num=inum, then it's a palindrome
if(num==inum){
return num; //Return sum to end <--- change here
}else{
sum=num+inum; //sum = number + inverted number
printf("%d + %d = %d",num,inum,sum); //Print the previous sum
return calc(sum); <--- just call `calc` again.
}
}
之前您使用错误的参数调用 calc
,并且每次它都使用相同的数字进行分支,但下一次调用永远不会相同。无需在 calc()
中再次传递 sum = sum + calc(num);
num。这创建了无限循环。
还要解释一下我所做的更改 - 问题是每当你干运行算法时 - 你首先计算数字和反向数字,然后检查两者。如果它们不匹配,你会传递真实的数字吗?不。您传递它们的总和,这就是这里所做的。
关于c - C语言169算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48791655/