我正在做一个素数 no# 类(运行一个函数来检查 inout 是否为素数),并试图通过打印素数输入的素数来更进一步。正如您在代码中看到的那样,我设法通过在 cout 中间嵌入一个 for 循环来破解一个不优雅的解决方案。
我想编写一个函数来创建一个数组,该数组包含输入 num 可以除以的所有数字,然后在我的主函数中调用该函数。
int main() {
int num;
cout<<"Enter a number and we'll check if it's prime: ";
cin>>num;
isPrime(num);
if (isPrime(num) == true)
cout<<"Number is prime!";
else
{
cout<<"Not a prime number :( ";
cout<<"Infact, "<<num<<" can be divided by: ";
for(int i=2; i<num; i++) {
if(num % i == 0)
cout<<i<<", ";
}
//What I want:> cout<<"Infact, "<<num<<" can be divided by: "<<arrayOfDiiders;
}
return 0;
}
下面是类人类语言/c++代码,用来描述我想要实现的目标。
int allDividers(int num) {
int arrayOfDiiders[]; //the array i wanted to make
for(int i=2; i<num; i++) {
if(num % i == 0)
// add i to the arrayOfDiiders[];
}
return arrayOfDiiders[];
}
断言用户输入是否为质数的其他函数。包括相关情况。
bool isPrime(int num){
int countDivs = 0;
for(int i=1; i<=num; i++) {
if (num % i == 0)
countDivs++;
}
if (countDivs == 2)
return true;
else
return false;
}
提前致谢。
最佳答案
I managed to hack together an inelegant solution as you can see in the code, by wedging a for-loop in the middle of a cout.
实际上,这个解决方案要优雅得多,因为它避免了动态数组的不必要开销。
- Create dynamically filled array in a function. 2) Return the array content
你可以这样做:
std::vector<int> v; // a dynamic array
// fill the vector here
return v;
关于c++ - 1) 在函数中创建动态填充的数组。 2)返回数组内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70572831/