如何输出变量可被整除的数字?

时间:2013-02-24 20:06:42

标签: c++ variables

抱歉,我的电子课程作业遇到了麻烦。 我被要求编写一个程序,该程序确定用户的输入数字是否为素数,然后表示其素数,或者它给出输入可分割的数字。 我应该使用哪种语法来实现它? 例如:“6可分为6; 3; 2; 1” 到目前为止,这是我的代码:

   #include<iostream>
   #include<conio.h>  
   using namespace std;
   int main()  
   {
   int P,count=0;
   cout<<"Enter a number:\n"; /*Asks for user input*/
   cin>>P;                    /* User input P*/
   for(int a=1;a<=P;a++)
   {
   if(P%a==0)
   {
   count++;
   }
   if(count==2)
         {
        cout<<"Prime number.\n";  /* Provided option when the number is prime number*/
         }
       else
        {
          cout<<" Not prime number \n"; /* This is where I am supposed to provide the               numbers input is divisible with*/
        }
   getch();
   } 
   }

1 个答案:

答案 0 :(得分:2)

不完全确定错误,但您的程序会打印类似

的内容
Enter a number:
6
 Not prime number 
Prime number.
 Not prime number 
 Not prime number 
 Not prime number 
 Not prime number

此外,<conio.h>不是标准C ++。我建议你写这样的东西(注意使用std::vector积累除数):

#include <iostream>
#include <vector>

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

    if (n == 0) {
        "Not a prime; 0 is divisible by all integers";
        return 0;
    }

    std::vector<int> divisors;

    for (int i = 1; i <= n; i++) {
        if (n % i == 0) {
            divisors.push_back(i);
        }
    }

    if (divisors.size() > 2) {
        std::cout << "Not a prime; divisors:" << std::endl;
        for (std::vector<int>::iterator it = divisors.begin(); it != divisors.end(); it++) {
            std::cout << *it << std::endl;
        }
    } else {
        std::cout << "Prime" << std::endl;
    }

    return 0;
}