如何输出变量可除数

How do I output the numbers which the variable is divisable with?

本文关键字:变量 输出 何输出      更新时间:2023-10-16

对不起,我的电子课程作业有问题。我被要求编写一个程序,确定用户输入的数字是否是素数,然后说出它的素数,或者给出输入可除的数字。我应该使用哪种语法来实现它
例如:"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();
   } 
   }

不完全确定出了什么问题,但您的程序打印出类似的东西

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;
}