c++ - 1) 在函数中创建动态填充的数组。 2)返回数组内容

标签 c++

我正在做一个素数 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.

实际上,这个解决方案要优雅得多,因为它避免了动态数组的不必要开销。

  1. 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/

相关文章:

c# - 如何使用 Win32/User32 库检查当前鼠标按钮状态?

c# - 将自定义类型的 Safearray 从 C++ 传递到 C#

C++ - 以对数读取列表,在给定位置插入

c++ - 创建类的二维数组

c++ - 为什么 *= 运算符没有按我预期的方式运行?

c++ - 从我的二维数组中的一列返回的字符串值被压缩成一个字符串(在 Mac 操作系统上打开 Windows txt 文件)

支持时间运算的C++标准库

C++0x 原子模板实现

c++ - 构建 Qt 示例不提供相同的输出,窗口自定义

c++ - 浮点计算使用 float 的结果与使用 double 的结果不同