马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
我们老师让我们输入一个最小的数字a,然后输入一个最大的数字b,然后分别判断在range[a,b]中有多少个素数,然后输出:
输出的格式如下:
There are xxxx primes in the range[a,b]
我有个问题就是我不知道这个range【】是怎么用,我用cout输出这个range电脑一直说我未定义,求求大神们帮帮我#include <iostream>
using namespace std;
int main() {
bool flag = true;
int a, b, i, j, times = 0;
cout << "please enter a positive integer as the minimum:" << '\n';
cin >> a;
cout << "please enter a positive integer as the maximum:" << '\n';
cin >> b;
for (i = a; i <= b; i++) // read the numbers from a to b
{
for (j = 2; j <= i / 2; j++)
{
if (i % j == 0) // judging each number if it is not a prime
{
flag = false;
}
}
if (flag)
{
times += 1; // if it is prime, counting
} else {
times = times;
flag = true; //return true so as to judge another number
}
}
cout << "There are " << times << " primes in the " <<range[a,b]<<'\n';
return 0;
}
本帖最后由 superbe 于 2019-9-10 08:58 编辑
#include <iostream>
using namespace std;
int main() {
bool flag = true;
int a, b, i, j, times = 0;
cout << "please enter a positive integer as the minimum:" << '\n';
cin >> a;
cout << "please enter a positive integer as the maximum:" << '\n';
cin >> b;
for (i = a; i <= b; i++) // read the numbers from a to b
{
for (j = 2; j <= i / 2; j++)
{
if (i % j == 0) // judging each number if it is not a prime
{
flag = false;
break; //添加这行
}
}
if (flag)
{
times += 1; // if it is prime, counting
} else {
//times = times; //去掉这行
flag = true; //return true so as to judge another number
}
}
cout << "There are " << times << " primes in the " << "range[" << a << "," << b << "].\n";
return 0;
}
range是“范围”的意思,range[a,b]表示"从a到b的范围",除了a,b原样输出就可以了。range加双引号就是按字符串输出,否则就被当作变量而前面确实没定义range这么个变量。
另外代码中有两处小修改(红色注释行),不改结果也没错,但是多做了无用功。
|