C++编写 回文数出错 请指教

编程实战营 2012-12-27 09:25:37
#include <iostream>
#include <string>
using namespace std;
using std::string;

int main()
{
string s;
string::size_type i;
int count=0;
cin>>s;
string::size_type N = 0;
N = s.size();
for (i=0;i<=s.size()/2;i++,N--)
{
if (s[i]==s[N-1])
{
++count;
}
else continue;

}
if (int(N/2)==count)
{
cout<<s<<"是回文数"<<endl;
}
else
{
cout<<s<<"不是回文数"<<endl;
}
getchar();
return 0;

}

这是我写的程序,但是输出结果就是不对,希望大家帮我看看,或者告诉我怎么去调试这个程序和思路?我自己去弄
...全文
162 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
abc41106 2012-12-27
  • 打赏
  • 举报
回复
楼主的代码有两处错误: 1.for (i=0;i<=s.size()/2;i++,N--),不应该是<=,按道理应该是1~s.size()/2,但是数组下标从0开始,所以应是< 2.if (int(N/2)==count),不应该用N,因为你循环里面已经把N减掉了。
#include <iostream>
#include <string>
using namespace std;
using std::string;

int main()
{
string s;
string::size_type i;
int count=0;
cin>>s;
string::size_type N = 0;
N = s.size();
for (i=0;i<s.size()/2;i++,N--)
{
if (s[i]==s[N-1])
{
++count;
}
else continue;

}

if (int(s.size()/2)==count)
{
cout<<s<<"是回文数"<<endl;
}
else
{
cout<<s<<"不是回文数"<<endl;
}
getchar();
return 0;

}
另外,楼主可以参考楼上的方法,不需要计数的。
lilianjie001 2012-12-27
  • 打赏
  • 举报
回复
#include <iostream>
#include <string>
using namespace std;
using std::string;

int main()
{
	string s;
	string::size_type i;
	int count=0;
	cin>>s;
	getchar();
	string::size_type N = 0;
	N = s.size();
	for (i=0;i<=s.size()/2;i++,N--)
	{
		if (s[i]==s[N-1])
		{
			++count;
		}
		else break;

	}
	if (int(s.size()/2 + 1)==count)
	{
		cout<<s<<"是回文数"<<endl;
	}
	else
	{
		cout<<s<<"不是回文数"<<endl;
	}
	return 0;

}
别逗我乐 2012-12-27
  • 打赏
  • 举报
回复
回文数,一般的思路是,依次取出每位的数,乘起来,看看和原先是否相等 9876 == (( 9*10+8 )*10 +7 )*10 +6
szulee 2012-12-27
  • 打赏
  • 举报
回复
用你的代码 试了几个数字 都显示正确 不知楼主输入什么数不对了。 另外 可以稍微简化下:
#include <iostream>
#include <string>
using namespace std;
using std::string;

int main()
{
	string s;
	string::size_type i;
	//int count=0;
	cin>>s;
	string::size_type N = 0;
	N = s.size();
	for (i=0;i<=s.size()/2;i++,N--)
		{
			if (s[i]!=s[N-1])
				{
					cout<<s<<"不是回文数"<<endl;
					getchar();
					return 0;
				}
				
		}
	cout<<s<<"是回文数"<<endl;
	getchar();
	return 0;

}
别逗我乐 2012-12-27
  • 打赏
  • 举报
回复
if (s[i]==s[N-1]) { ++count; } else break;//没有必要继续下去了
编程实战营 2012-12-27
  • 打赏
  • 举报
回复
引用 2 楼 szulee 的回复:
用你的代码 试了几个数字 都显示正确 不知楼主输入什么数不对了。 另外 可以稍微简化下: C/C++ code?12345678910111213141516171819202122232425262728#include <iostream>#include <string>using namespace std;using std::string; int ……
非常感谢2楼,当然也感谢大家,你提供的这个让我理解的更深刻了,因为不成立的情况比较多,所以先判断no的情况是更加合适的

64,648

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧