我是 C# 新手,正在做这个程序作为练习。我已经设法让我的程序打印用户给出的输入的倒数,但是当我继续检查它是否是回文时,它不能正确计算答案。它总是打印“不是回文”。
经过一些错误检查后,我意识到这样做的原因是因为存储newnum
的最后一个数字只是反转后的最后一个数字,而不是整个数字。我该如何纠正这个?
我的代码
int i, remainder = 0, newnum = 0;
Console.WriteLine("Enter a Number: ");
int uinput = Convert.ToInt32((Console.ReadLine()));
for (i = uinput; i > 0; i = (i / 10))
{
remainder = i % 10;
Console.Write(remainder);
newnum = remainder;
}
if (newnum == uinput)
{
Console.WriteLine("The Number {0} is a palindrome", uinput);
}
else
{
Console.WriteLine("Number is not a palidrome");
}
Console.WriteLine(uinput);
Console.WriteLine(newnum);
Console.ReadKey();
}
我还在网上查看了另一个代码示例,但我不明白的是为什么 num 在 while 循环中被转换为布尔类型?这只是为了保持循环运行吗?
上面提到的代码
int num, rem, sum = 0, temp;
//clrscr();
Console.WriteLine("\n >>>> To Find a Number is Palindrome or not <<<< ");
Console.Write("\n Enter a number: ");
num = Convert.ToInt32(Console.ReadLine());
temp = num;
while (Convert.ToBoolean(num))
{
rem = num % 10; //for getting remainder by dividing with 10
num = num / 10; //for getting quotient by dividing with 10
sum = sum * 10 + rem; /*multiplying the sum with 10 and adding
remainder*/
}
Console.WriteLine("\n The Reversed Number is: {0} \n", sum);
if (temp == sum) //checking whether the reversed number is equal to entered number
{
Console.WriteLine("\n Number is Palindrome \n\n");
}
else
{
Console.WriteLine("\n Number is not a palindrome \n\n");
}
Console.ReadLine();
非常感谢任何形式的帮助!谢谢你 :)