【问题标题】:Prime-testing program not workingPrime 测试程序不起作用
【发布时间】:2016-03-12 09:40:38
【问题描述】:
#include "stdafx.h"
#include "math.h"
#include <string>
#include <iostream>

using namespace std;

int main ()
{
    int x;
    cout << "Enter a number." << endl;
    cin >> x;
    int y = 1;
    int i = 0;
    while (i == 0 && y < sqrtf(x))
    {
        if (fmodf(x,y) == 0)
        {
            i = 1;
        }
        else
        {
            i = 0;
        }
        y++;
    if (i == 1)
    {
        cout << "Your number is prime." << endl;
    }
    else 
    {
        cout << "Your number is composite." << endl;
    }
    }
    return 0;
}

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

它打开命令窗口,读取“输入数字”,然后在我输入数字的第二次关闭。

帮助?

【问题讨论】:

  • 你为什么要使用fmodf

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


【解决方案1】:

你必须:

  • 在正确的位置关闭while 循环
  • 更改if (i == 1) 条件(i==1 表示x 可以被某些y 整除)
  • y = 2 开头(每个数字都可以被一整除)
  • 包括 sqrtf(x) 在循环中(y &lt;= 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;
}

现在:

【讨论】:

  • 这很有用。但是我如何阻止它在输出的那一刻关闭呢?有这样的设置吗? (我使用 Microsoft Visual C++ 2010 Express)
猜你喜欢
  • 2012-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-26
相关资源
最近更新 更多