C++ 重复循环回文
检查5个条目是否为回文,我编写的代码会为第一个条目提供正确的输出,但不会为其余条目提供正确的输出。我已经试运行了代码,但找不到错误所在 代码如下:C++ 重复循环回文,c++,loops,palindrome,C++,Loops,Palindrome,检查5个条目是否为回文,我编写的代码会为第一个条目提供正确的输出,但不会为其余条目提供正确的输出。我已经试运行了代码,但找不到错误所在 代码如下: while (count < 5) { cin >> n; store = n; while (n > 0) { reverse = reverse * 10 + n % 10; n = n / 10;
while (count < 5)
{
cin >> n;
store = n;
while (n > 0)
{
reverse = reverse * 10 + n % 10;
n = n / 10;
}
if (store == reverse)
cout << "it's a palindrome " << endl;
else
cout << "Not a palindrome " << endl;
count++;
}
while(计数<5)
{
cin>>n;
存储=n;
而(n>0)
{
反向=反向*10+n%10;
n=n/10;
}
如果(存储==反向)
cout您没有在两次运行之间重置reverse
。在循环开始处添加reverse=0;
:
#include <iostream>
int main() {
int count = 0, store = 0, n = 0;
int reverse = 0;
while (count < 5)
{
reverse = 0;
std::cin >> n;
store = n;
while (n > 0)
{
reverse = reverse * 10 + n % 10;
n = n / 10;
}
if (store == reverse)
std::cout << "it's a palindrome " << std::endl;
else
std::cout << "Not a palindrome " << std::endl;
count++;
}
}
#包括
int main(){
整数计数=0,存储=0,n=0;
int反向=0;
同时(计数<5)
{
反向=0;
标准:cin>>n;
存储=n;
而(n>0)
{
反向=反向*10+n%10;
n=n/10;
}
如果(存储==反向)
std::cout您应该在while循环中首先声明reverse
,因为如果不声明reverse
,则仍将保留上一次迭代的值并产生错误的结果。如下所示:
while (count < 5)
{
cin >> n;
store = n;
int reverse=0; // <--- declare here;
while (n > 0)
{
reverse = reverse * 10 + n % 10;
n = n / 10;
}
if (store == reverse)
cout << "it's a palindrome " << endl;
else
cout << "Not a palindrome " << endl;
count++;
}
while(计数<5)
{
cin>>n;
存储=n;
int reverse=0;//0)
{
反向=反向*10+n%10;
n=n/10;
}
如果(存储==反向)
您是否没有重新初始化反向
请尝试创建一个显示给我们。对于存储
和n
也一样。