Prime测试程序不起作用

时间:2016-03-12 09:40:39

标签: c++ algorithm visual-c++ primes

class Machine {
   void buy1(){}
   void buy2(){}
   void buy2(){}
   public static void main(String args[]) {
      Machine obj = new Machine();

      obj.buy1();
      .....
  }
}

这是我为测试素数而创建的代码。在整理出几个调试问题之后,我就可以运行它了。

它打开了命令窗口,读取“输入一个数字”并在我输入数字的第二个时自行关闭。

帮助?

1 个答案:

答案 0 :(得分:1)

你必须:

  • 在正确的位置关闭while循环
  • 更改if (i == 1)条件(i==1表示x可被某些y整除}
  • y = 2开头(每个数字可被1整除)
  • 循环中
  • 包含 sqrtf(x)y <= sqrtf(x)或15,25,35 ...是素数)。

所以:

int main()
{
  int x;
  cout << "Enter a number." << endl;
  cin >> x;

  int y = 2;  // <-- changed
  int i = 0;

  while (i == 0 && y <= sqrtf(x))  // <-- changed
  {
    if (fmodf(x,y) == 0)
    {
        i = 1;
    }
    else
    {
        i = 0;
    }

    y++;
  }  // <-- moved here

  if (i == 0)  // <-- changed
  {
    cout << "Your number is prime." << endl;
  }
  else
  {
    cout << "Your number is composite." << endl;
  }

  return 0;
}

有效(或多或少......)。

反正:

有点好(但远非完美):

#include <cmath>
#include <iostream>

int main()
{
  int x;
  std::cout << "Enter a number.\n";
  std::cin >> x;

  int square_root = std::sqrt(x);
  int y = 2;
  int i = 0;
  while (i == 0 && y <= square_root)
  {
    if (x % y == 0)
      i = 1;

    ++y;
  }

  if (i == 0)
    std::cout << "Your number is prime.\n";
  else
    std::cout << "Your number is composite.\n";

  return 0;
}

现在:

相关问题