动态数组和功能

时间:2014-10-31 06:01:46

标签: c++ arrays function dynamic-arrays

我正在尝试做我的项目而且我被困住了。如果我理解的话,我的教授希望我使用动态数组,以及比较整数并得到他们的GCD的函数。我不能使功能工作。有什么想法吗? 这是舞会:

编写一个程序来计算任何有限整数集的最大公约数。使用函数计算GCD。集合中的元素数量不应预先确定。您需要编写代码,在输入数据时,将计算集合中的数量。基于Euclid的算法左右。

我输入10,100和40,GCD应为10;但是,我得到了这个结果:

The GCD of:  is: 
   10         0    
  100         0
   40         0
  

#include <iostream>
#include<iomanip>

using namespace std;

int greatestdivisor(int b[], int size); /*Write prototype for gcd */

int main()
{
    int greatest;
    int max=1;
    int* a= new int[max]; //allocated on heap
    int n=0;

    cout<<"Input numbers: "<<endl;
    cout<<"Hit Enter key after each input and type any letter to finish"<<endl;

    while(cin>>a[n]){     //read into array
        n++;
        if(n>=max){
            max=n;   //increase size of array
            int* temp = new int[max];    //creates new bigger array

            for(int i=0;i<n;i++){
                temp[i] = a[i];   //copy values to new array
            } //end for
            delete [] a;     //free old array memory
            a = temp;     //a points to new array
        } //end if

    } // end while
    cout<<endl;
    greatest = greatestdivisor(a, max);
    cout<<"The GCD of: "<<" is: "<<endl;
    for(int j=0;j<max;j++)
        cout<<setw(5)<<a[j]<<setw(10)<<greatest<<endl;
    n++;// prints elements of array and call function
} // end main

// gcd finds greatest common divisor of array
int greatestdivisor(int b[], int size)
{
    int greatest =1;// current greatest common divisor, 1 is minimum

    for (int x=0; x<=size; x++) {
        int m=b[x];
        int r=2;
        if(m%r==0){
            greatest =m; // update greatest common divisor
        } //end if
    } // end for
    return greatest; //return gcd
} // end fuction gcd

3 个答案:

答案 0 :(得分:2)

您的代码中存在许多问题,try this并弄清楚您做错了什么:

#include <iostream>
#include<iomanip>

using namespace std;

int greatestdivisor(int b[], int size); /*Write prototype for gcd */

int main()
{
    int greatest;
    int max=1;
    int* a= new int[max]; //allocated on heap
    int n=0;

    cout<<"Input numbers: "<<endl;
    cout<<"Hit Enter key after each input and type any letter to finish"<<endl;

    while(cin>>a[n]){     //read into array
        n++;
        if(n>=max){
            max=n+1;   //increase size of array
            int* temp = new int[max];    //creates new bigger array

            for(int i=0;i<n;i++){
                temp[i] = a[i];   //copy values to new array
            } //end for
            delete [] a;     //free old array memory
            a = temp;     //a points to new array
        } //end if

    } // end while
    cout<<endl;
    greatest = greatestdivisor(a, n);
    cout<<"The GCD of: "<<" is: "<<endl;
    for(int j=0;j<n;j++)
        cout<<setw(5)<<a[j]<<setw(10)<<greatest<<endl;
} // end main


int gcd(int a,int b)
{
    int t;
    while(a)
    {
        t = a;
        a = b%a;
        b = t;
    }
    return b;
}

// gcd finds greatest common divisor of array
int greatestdivisor(int b[], int size)
{
    int greatest =b[0];// current greatest common divisor, 1 is minimum

    for (int x=1; x<size; x++) {
        greatest = gcd(greatest, b[x]); // update greatest common divisor
    } // end for
    return greatest; //return gcd
} // end fuction gcd

答案 1 :(得分:2)

您的GCD算法已损坏。它应该是从前两个条目开始,找到数组中每个连续值的GCD。对于数组中的所有条目重复,最终的gcd将在所有条目中共同使用。正如评论中所提到的,你的(破碎的)gcd迭代算法中的大小也是错误的;它应该严格地小于。

一个很简单的版本看起来像这样:

#include <iostream>
#include <iomanip>
#include <cmath>

static int gcd(const int b[], size_t size);

int main()
{
    int* a = nullptr, value=0;
    size_t n = 0;

    std::cout<<"Input numbers:\n";
    while(std::cin >> value)
    {
        int *temp = new int[n+1];
        std::copy(a, a+n, temp);
        delete [] a;
        a = temp;
        a[n++] = value;
    }

    std::cout<<"The GCD is " <<  gcd(a, n) << '\n';
    delete [] a;
}

static int gcd(const int b[], size_t size)
{
    int res = (size > 0 ? std::abs(b[0]) : 0);
    for (size_t x=1; x<size; ++x)
    {
        int n = std::abs(b[x]);
        while (n > 0)
        {
            auto tmp = res;
            res = n;
            n = tmp % n;
        }
    }
    return res;
}

<强>输出

Input numbers: 
10
100
40
x
The GCD is 10

让世界变得更美好:std::vector

既然你可以看到一个手动管理的动态数组如何工作,我就不能强调这一点可以通过而不是首先做到这一点,而只是简单地使用来自标准库。 std::vectorstd::istream_iterator将完成此任务的简短工作,并且代码变得非常容易出错。您可以使用std::vectorint获得动态内存管理,并使用std::istream_iterator格式化输入复制到EOF或非#include <iostream> #include <vector> #include <iterator> #include <iomanip> #include <cmath> static int gcd(const int b[], size_t size); int main() { std::cout<<"Input numbers:\n"; std::vector<int> a((std::istream_iterator<int>(std::cin)), std::istream_iterator<int>()); std::cout<<"The GCD is " << gcd(a.data(), a.size()) << '\n'; } static int gcd(const int b[], size_t size) { int res = (size > 0 ? std::abs(b[0]) : 0); for (size_t x=1; x<size; ++x) { int n = std::abs(b[x]); while (n > 0) { auto tmp = res; res = n; n = tmp % n; } } return res; } 数据。简而言之,几乎所有数据管理都是为您处理的。

看看:

{{1}}

输出与以前相同。祝你好运

答案 2 :(得分:1)

如果完全以您描述的方式指定问题,则似乎没有明确要求array

因此,您可以简化为

#include <vector>
#include <iostream>
#include <sstream>

int greatestdivisor(std::vector<int> &ints);
int euclid(int a, int b);

int main()
{
    std::vector<int> listOfInts;
    std::string line = "default";
    int tempInt=0;

    std::cout << "Description" << std::endl;

    while (line.length() != 0)
    {
        std::getline(std::cin, line);
        std::stringstream temp(line);
    temp >> tempInt;
    listOfInts.push_back(tempInt);
    }
    listOfInts.pop_back(); // Remove the last entry, which is counted twice by this while loop :/

    for (int i=0; i< listOfInts.size(); i++)
    {
      std::cout<< listOfInts[i] << std::endl;
    }

    int gcd = greatestdivisor(listOfInts);
    std::cout << "gcd = " << gcd << std::endl;
}

int greatestdivisor(std::vector<int> &ints)
{
  int currentGCD = ints[0];
  while (ints.size() > 0)
  {
    int a = ints.back();
    ints.pop_back();
    currentGCD = euclid(a, currentGCD);
    std::cout <<  "currentGCD = " << currentGCD << std::endl;
  }
  return currentGCD;
}

int euclid(int a, int b)
{
  if (b == 0)
    return a;
  else
    return euclid(b, a % b);
}