c ++使用函数打印给定数字的素数因子的程序

时间:2018-03-25 22:40:09

标签: c++

我需要帮助!!

我希望有人可以帮助我使用我的硬件代码。目标是构建一个代码,使用函数显示许多用户给定数字的素数因子(函数是我们在课堂上看到的最高级的主题)。我以某种方式达到了目标。让我告诉你输出应该怎么样:

 Enter a number greater than 1: 10
 Prime factors of 2: 2
 Prime factors of 3: 3
 Prime factors of 4: 2 2
 Prime factors of 5: 5
 Prime factors of 6: 2 3 
 Prime factors of 7: 7
 Prime factors of 8: 2 2 2 
 Prime factors of 9: 3 3
 Prime factors of 10: 2 5

然而我的输出是这样的:

 2 the prime factors of 2 are: 0
 3 the prime factors of 3 are: 0
 2 2 the prime factors of 4 are: 0
 5 the prime factors of 5 are: 0
 2 3 the prime factors of 6 are: 0
 7 the prime factors of 7 are: 0
 2 2 2 the prime factors of 8 are: 0

这是我的代码:

  #include <iostream>
   using namespace std;

    int factorIt(int a){
    if (a==1){ return 0;}
    int b=2;
    while (a%b !=0) b++;
    cout << b << " ";
    factorIt(a/b);
  }

   int main (){
    int n;
    cout << "enter a number greater than 1: ";
    cin >> n;
    for (int a=2; a <= n; a++){
    cout << "the prime factors of " << a << " are: "<< factorIt(a) << endl;

    }
    return 0;
 }

为什么首先打印功能输出?如何修复代码并使其看起来像所需的输出?如果你帮我这个,我将不胜感激。提前致谢

1 个答案:

答案 0 :(得分:1)

您正在混合计算和输出,这几乎不是一个好主意。如您所见,输出语句中术语的评估顺序未指定 - 它可以按任何顺序发生。

无论如何,factorIt函数确实没有返回因子,因此在cout语句中它没有用处。

如果您改为void factorIt(int)并单独调用它,您将获得预期的输出。

cout << "the prime factors of " << a << " are: ";
factorIt(a);
cout << endl;