动态数组和函数

Dynamic Array and function

本文关键字:函数 数组 动态      更新时间:2023-10-16

我正在努力完成我的项目,但我被卡住了。如果我理解的话,我的教授希望我使用一个动态数组,以及一个比较整数并获得其GCD的函数。我无法使功能正常工作。有什么想法吗?这是毕业舞会:

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

I输入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

您的代码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

您的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::vector获得动态内存管理,并使用std::istream_iterator将格式化的输入复制到EOF或非int数据。简而言之,几乎所有数据管理方面的事情都是为您处理的。

看看:

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

输出与以前相同。祝好运

如果问题完全按照您描述的方式指定,那么似乎不需要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);
}