【发布时间】:2016-12-03 08:40:36
【问题描述】:
这段代码运行良好,它告诉你输入一个数字,然后输入 for 循环中的数字,它检查它是否可以被 i 整除,如果为真,则打印非素数,如果不打印素数。
#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";
}
}
但是当我将它转换为这样的数组时:
#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]
【问题讨论】:
-
请告诉我为什么你投了反对票,这样我就可以修复它。如果我的问题很愚蠢,我只是 C++ 的新手。
-
我没有投反对票,但确实不清楚你在问什么。代码太多,没有足够的精力来查明问题。调试器在这里可能很方便。顺便说一句,它不是“主要”数字,而是“主要”数字。
-
@Jean-FrançoisFabre 我会尝试进一步解释谢谢。
-
我不明白你的问题。
-
这段代码运行良好....我敢打赌你有一台量子计算机!不,我的朋友,第一段代码也是完全错误的。