查找指针数组中的主要数字 [英] Finding the primary numbers in an array of pointer
问题描述
这段运行良好的代码告诉你输入一个数字,然后它把for 循环中的数字,它检查它是否可以被 i 整除,如果为真,则打印不是素数,如果不是则打印素数.
This piece of code which works fine it tells you to enter a number, then it puts the number in a for loop and it checks if it's dividable by i, if true it prints not prime if not prints prime.
#include <iostream>
using namespace std;
int main() {
int x;
cin >> x;
bool f = true;
for (int i = 2; i < x; i++) {
f = false;
if (i % x == 0)
f = true;
if (f)
cout << "not primary";
else
cout << "primary";
}
}
但是当我将其转换为这样的数组时:
but when i convert it to an array like so:
#include <iostream>
using namespace std;
int main() {
cout << "the number of array:" << endl;
int n;
cin >> n;
cout << "enter them = \n";
int *p = new int[n];
for (int i = 0; i < n; i++)
cin >> p[i];
bool f = true;
for (int i = 0; i < n; i++)
for (int j = 2; j < p[i]; j++) {
f = false;
if (p[i] % j == 0)
f = true;
if (f)
cout << "This is not a primary number!\n";
else
cout << "this is a primary number!\n";
}
delete p;
}
它只存储第一个数字,我明白了,但如何增加它假设 n = 3所以 p[3] = {4,6,7};我的问题是如何在 j 条件下告诉编译器if (p[0] % j) then(p[1] %j) 似乎只需要 p[0]
it stores just the first number and i get that but how to increment it lets say n =3 so p[3] = {4,6,7}; my question is how tell the compiler in the j condition if (p[0] % j) then(p[1] %j) it seems that it just takes p[0]
推荐答案
这样效果会更好
#include <iostream>
using namespace std;
int main() {
cout << "the number of array:" << endl;
int n;
cin >> n;
cout << "enter them = \n";
int *p = new int[n];
for (int i = 0; i < n; i++)
cin >> p[i];
for (int i = 0; i < n; i++) {
bool f = false; // we set f to false for each number
for (int j = 2; j < p[i]; j++) {
if (p[i] % j == 0) {
f = true;
break; // we break the loop if it's a prime number
}
}
if (f)
cout << p[i] << " is not a primary number!\n";
else
cout << p[i] << " is a primary number!\n";
}
delete[] p; // Here you forget brackets [], when you use new[] you must use delete[].
}
Doc 用于删除运算符.
我让一些问题像int
.您不应该使用带符号的数字进行迭代或存储尺寸.因为你是初学者,我不想迷惑你.所以我让了.
I let some problem like int
. You should not use signed number for iteration or stock a size. Because you are a beginner, I don't want to confuse you. So I let it.
这篇关于查找指针数组中的主要数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!