在指针数组中找到主要数字

Finding the primary numbers in an array of pointer

本文关键字:数字 指针 数组      更新时间:2023-10-16

这件代码正常,它告诉您输入一个数字,然后将其放置for循环中的数字,并检查它是否可以由i划分,如果TUE,如果不打印质量,则不会打印出来。

#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条件下告诉编译器如果(p [p [0]%j),则(p [1]%j)似乎只服用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[].
}

删除操作员的文档。

我让诸如int之类的问题。您不应将签名的号码用于迭代或库存尺寸。因为您是初学者,所以我不想让您感到困惑。所以我让它。