gpt4 book ai didi

c - 在 C 编程中设置循环限制并计算回文

转载 作者:行者123 更新时间:2023-11-30 17:08:17 25 4
gpt4 key购买 nike

所以这段代码的目标是将用户号转换为回文。如果该数不是回文数,则计算该数+反转数,直到成为回文数。如果仍然不是回文,则取最后一个数字的总和并将其反转并将其相加,最多尝试 10 次。

int main()
{
int n;
int reverse = 0; //initial value will be 0
int temp; //temporary variable

//Check if number is a palindrome===============================

printf("Enter an integer: ");
scanf_s("%d", &n);
temp = n; //Make input number have a temporary variable

while (temp != 0)
{
reverse = reverse * 10;
reverse = reverse + temp % 10;
temp = temp / 10;
}

//Check if number entered by user and it's reverse number is equal
if (reverse == n)
printf("%d\t1, reverse is %d\n", n, reverse); //Is a palindrome
else
printf("%d\t0, reverse is %d\n", n, reverse); //Not a palindrome
//==========================================================================

//Keep adding numbers until it reaches a palindrome
int sum;

while (n /= reverse)
{
sum = n + reverse;
n++;
}

if (reverse == sum)
printf("%d it works", sum, reverse);
else
("%d didn't work", sum, reverse);

我还没有达到极限。但我的问题是,如何将逆序和用户号码相加,然后求和+其逆序?另外,什么样的循环最适合此类问题?

最佳答案

你可以做的就是在另一个 while 循环(考虑为循环 1)中编写用于生成数字相反的 while 循环(考虑为循环 2),当数字是回文时,该循环会中断(终止)。如果给定的数字不是回文,那么您将数字更改为 number=number+reverse。如果您想尝试 10 次,那么您可以通过使用计数器为循环 1 添加另一个条件。下面是我写的代码。

#include<stdio.h>
int main()
{
int n;
int count=0; //taking counter for number of trials
int reverse=0; //initial value will be 0
int temp; //temporary variable

printf("Enter an integer: ");
scanf("%d", &n);

while (count<10)
//count less than 10 condition makes the max. no. of trials equal to 10
{
temp=n; //assigning a temporary variable to n
reverse=0;
//Finding the reverse of the number n===============================
while (temp != 0)
{
reverse = reverse * 10;
reverse = reverse + temp % 10;
temp = temp / 10;
}

//Check if number entered by user and it's reverse number is equal
if (reverse == n){
printf("\n%d\t1, reverse is %d\n", n, reverse);
//Is a palindrome
break;
/*break condition makes the loop 1 to terminate if the number 'n' is palindrome*/
}
else
printf("\n%d\t0, reverse is %d\n", n, reverse);
//Not a palindrome
//================================================================

//Keep adding numbers until it reaches a palindrome
n=n+ reverse;
count++;
}
}

关于c - 在 C 编程中设置循环限制并计算回文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33747756/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com