简体   繁体   English

C ++帮助无法正常工作

[英]C++ Help can't get it work

Write a program that generates all the factors of a number entered by the user. 编写一个程序,该程序生成用户输入的数字的所有因数。 For instance, the number 12 has the factors 2 * 2 * 3. This program has the following requirements: 例如,数字12具有因子2 * 2 *3。此程序具有以下要求:

  1. The user must enter a positive integer. 用户必须输入一个正整数。 If the user enters something else, your program should output an error message and let the user enter a new value. 如果用户输入其他内容,则程序应输出一条错误消息,并让用户输入新值。 Use a do/while loop to make sure the user input is successful. 使用do / while循环来确保用户输入成功。

  2. The factors must be output in increasing order. 必须按升序输出因子。 The lowest factor your program should report is 2. 您的程序应报告的最低系数是2。

  3. Your program should output 4 factors per line, each factor in a field of 10 characters. 您的程序应该每行输出4个因数,每个因数在10个字符的字段中。 (Hint: the number of factors output determines when to output endl!) (提示:输出因子的数量决定了何时输出endl!)

  4. You will need a while loop to report the factors. 您将需要一个while循环来报告这些因素。 Here are some helpful hints: 以下是一些有用的提示:

    1. If (a % b == 0) then a is a factor of b. 如果(a%b == 0)则a是b的因数。

    2. When you have found a factor, output the factor and then reduce the number you are working with by dividing the number by the factor… ie) b = b / a; 找到因子后,输出因子,然后通过将因子除以因子来减少正在使用的因子的数量。即:b = b / a;

I have this code I can't get it to display the factors. 我有这段代码,我无法显示这些因素。 After you enter the number it just ends with out displaying the factors. 输入数字后,它仅以不显示因子结尾。

#include<iostream>

using namespace std;

int factor(int& n)
{
  for(int k=2; k<=n; k++)
    if(n%k==0)
    {
      n = n/k;
      return k;
    }
}


int main()
{
  int n;
  int p=0;

  do
  {
    cout << "Enter a Positive Integer :";
    cin >> n;
  } while(n<=0);

  cout << "Factors are " << endl;

  while(1)
  {
    if(n==1) break;
    cout << factor(n) << " ";
    p++;
    if(p%4==0) 
      cout << endl;   // new line after every 4 factors !!

    system("pause");
    return 0;
  }
}

It's difficult to see due to your (lack of) indentation, but this part : 由于缩进(缺少),很难看到,但是这部分:

system("pause");
return 0;

is inside the while(1) loop. while(1)循环中。 It should be outside of the while loop. 它应该在while循环之外。

So after indentation it is clear that : 因此,缩进后很明显:

 while(1)
 {
  if(n==1) break;
  cout << factor(n) << " ";
  p++;
  if(p%4==0) 
    cout << endl;   // new line after every 4 factors !!

  system("pause");
  return 0;
 }

After just calculating and printing the first factor you return from main. 在仅计算并打印第一个因子后,您将从main返回。 So please indent the code and keep proper formatting. 因此,请缩进代码并保持正确的格式。 Also even if you have single line under if , for etc, enclose them in braces. 此外,即使您在iffor等下面有单行,也请用大括号括起来。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM