注册 登录
编程论坛 C++教室

求教C++素数与对称的问题

zfan85 发布于 2010-08-30 01:37, 697 次点击
大家好,小弟是初学C++,遇到判断100~999中即是素数又是对称数(就是正反又是一样的,比如121倒过来还是121)的问题。
下面的程序得出的结果就是一致输出1,不知道为什么?
#include<iostream>
#include<cmath>
using namespace std;
main(){
    int a,b;
    for(int i=100;i<=999;i++){
        b=i;
        for(int j=2;j<=sqrt(i);j++)
            if(i%j==0) break;
            if(j>sqrt(i)){
            a=0;
            while(i>0){
                a=i%10+a*10;
                i/=10;}
            if(b==a)
                cout<<b<<"\n";}}


}
5 回复
#2
寒风中的细雨2010-08-30 08:49
            if(j>sqrt(i))
            {
                a=i%100;
                if( b%10 == a )
                    cout<<b<<"\n";
            }
#3
寒风中的细雨2010-08-30 08:54
#include<iostream>
#include<cmath>
using namespace std;

int main()
{
    int a;
    for(int i=100;i<=999;i++)
    {
        for(int j=2;j<=sqrt(i);j++)
            if(i%j==0)
                break;
        if( j>sqrt(i) )
        {
            a=i/100;
            if( i%10 == a )
                cout<<i<<"\n";
        }
    }
    return 0;
}
#4
zfan852010-08-30 12:33
谢谢  不过能解释一下我的为什么不可以啊?  
#5
南国利剑2010-08-30 13:57
看看这个可以吗?
程序代码:
#include<iostream>
#include<cmath>
using namespace std;

int main()
{
    int a(100);
    bool result(false);
    while(a<1000){
        for(int i=2;i<sqrt(a);i++)
            if(a%i==0)
            {
                result=true;
                break;
            }
        if(result==true)
        {
            int m,n;
            m=a%10;
            n=a/100;
            if(m!=n)
                result=false;
               
        }
        if(result==true)
            cout<<a<<endl;
        a++;
        result=false;
      
    }

    return 0;

}

 
#6
ragnaros2010-08-30 19:45
程序代码:
#include<iostream>
#include<cmath>
using namespace std;
main()
{
    int a,b;
    for(int i=100; i<=999; i++)
    {
        b=i;
        for(int j=2; j<=sqrt(i); j++)
            if(i%j==0) break;
            if(j>sqrt(i))
            {
                a=0;
                while(i>0)
                {
                    a=i%10+a*10;
                    i/=10;
                }
                //system("pause");
                if(b==a)
                    cout<<b<<"\n";
            }
        i=b; //这里i的值改回来,i的值在while循环之后等于0,也满足for(int i=100; i<=999; i++)这个要求,所以每次while循环完i=0.i++之后i=1

}
i=1的时候满足你的程序对素数和对称数的判断,因此在第一次循环输出101后,下面一直循环输出1。
因此只要把i的值改回循环之前的值即可。
1