程序功能:从键盘输入一个大于2的正整数n,求解并输出大小最接近n的素数(不包括n)。例如:
如输入:17
输则出:19
如输入:45
则输出:43 47
两个for循环分别向下和向上查找得到最近的素数n0和n1,判断其与n是否最近,如果距离相同则同时输出。
#include "stdafx.h"
#include <iostream>
using namespace std;
bool isp(int x)
{
for (int i = 2; i <= sqrt(x); i++)
{
if (x%i == 0)
return false;
}
return true;
}
int main()
{
int n,n1,n0;
cin >> n;
for (int i = n + 1; ; i++)
if (isp(i))
{
n1 = i;
break;
}
for (int i = n - 1;; i--)
if (isp(i))
{
n0 = i;
break;
}
if ((n1 - n) < (n - n0))
cout << n1<<endl;
else if((n1 - n) > (n - n0))
cout << n0<<endl;
else
cout << n0 << " " << n1 << endl;
system("pause");
return 0;
}
#include <stdio.h>
#include <math.h>
int fun(int n)
{
for(int i=2;i<n/2;i++)
if(n%i==0)
return 0;
return 1;
}
int main()
{
int num;
scanf("%d",&num);
for(int i=num-1,j=num+1;;i--,j++)
{
if(fun(i)&&fun(j))
{
printf("%d %d\n",i,j);
break;
}
if(fun(i)&&!fun(j))
{
printf("%d\n",i);
break;
}
if(!fun(i)&&fun(j))
{
printf("%d\n",j);
break;
}
}
return 0;
}
追问在GUIDE上运行有错误。
--------开始编译--------
4.4.c: In function `fun':
4.4.c:5: error: 'for' loop initial declaration used outside C99 mode
4.4.c: In function `main':
4.4.c:14: error: 'for' loop initial declaration used outside C99 mode
4.4.c:33:2: warning: no newline at end of file
编译结束但存在 2 错误 和 1 警告
不能编译
我用的vc++6.0可以运行呀
你把for循环里的i,j在for外面定义,然后再试试
我们要求用的是guide,所以不行。
谢谢了!